json-server icon indicating copy to clipboard operation
json-server copied to clipboard

Response data with X-Total-Count

Open vaishkish opened this issue 6 years ago • 4 comments

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.

vaishkish avatar Aug 23 '19 01:08 vaishkish

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);
  }
};

thepeted avatar Apr 07 '20 09:04 thepeted

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

d0whc3r avatar Apr 25 '20 11:04 d0whc3r

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

HighLiuk avatar Nov 30 '23 10:11 HighLiuk