Currently, I am working on an API using Express.js. In one of my functions named getAll, my goal is to not only return an array of records but also include the total number of records in the response. The code snippet below showcases how I have been handling this so far:
const users = await User.getAll()
const total = users.length
const response = users
return res.json(response).status(200)
The current format of the response looks like [{user1},{user2},{user3}]
. My question is: How can I modify it to append the total in the following format?
{ data: {Record[]}, total: {int} }
I attempted the following approach but it ended up adding a key for each user based on their ordinal position within the array.
const users = await User.getAll()
const total = users.length
const response = {
...users,
total
}
return res.json(response).status(200)