json-server
json-server copied to clipboard
Response data with X-Total-Count
What do I need to to convert the response object to return { TotalCount: X-Total-Count Data: [... dto goes here ] } Can I modify the response in middleware to return an object like above.
You can overwrite router.render method like this:
router.render = (req, res) => {
// add count meta to paginated requests
if (req.originalUrl.indexOf("_page") > -1) {
res.json({
results: res.locals.data,
meta: {
count: res.get("X-Total-Count"),
},
});
} else {
// send unmodified response
res.json(res.locals.data);
}
};
https://github.com/typicode/json-server/pull/1121
with this pr you can add an after middleware to modify response, like in router.render, but without creating a new server.js to execute json-server
you only need to add --midafter modifier.js like a middleware and you could use code from @thepeted
A bit late but this might help:
// middlewares.cjs
module.exports = (req, res, next) => {
const _send = res.send;
res.send = function (data) {
if (req.method === "GET") {
data = JSON.stringify({
Data: JSON.parse(data),
TotalCount: this.getHeader("X-Total-Count") ?? null,
});
}
_send.call(this, data);
};
next();
};
and run
json-server -m middlewares.cjs