Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response data with X-Total-Count #1015

Open
vaishkish opened this issue Aug 23, 2019 · 3 comments
Open

Response data with X-Total-Count #1015

vaishkish opened this issue Aug 23, 2019 · 3 comments

Comments

@vaishkish
Copy link

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.

@thepeted
Copy link

thepeted commented Apr 7, 2020

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

@d0whc3r
Copy link

d0whc3r commented Apr 25, 2020

#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

@HighLiuk
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants