json-server
json-server copied to clipboard
Query params from original URL and from modifications in middleware do not reflect on jsonServer.router.render's callback fn
I attempted to put default params in case the actual requests do not have _limit. Here is the following code
// node server.js
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./server/db.json');
const middlewares = jsonServer.defaults();
middlewares.push((req, res, next) => {
console.log('middleware reads', req.query)
if(req.originalUrl.indexOf("_limit") === -1)
req.query = { ...req.query, _limit: 10 }
next();
})
router.render = (req, res) => {
console.log('router reads', req.query)
res.json({
data: res.locals.data,
totalCount: res.get("X-Total-Count"),
page: req.query._page /* undefined*/ || 1,
limit: req.query._limit /* undefined*/ || 10
});
if(!req.query._limit) req.query._limit = 8;
};
server.use(middlewares);
server.use(router);
server.listen(3000, () => {
console.log('JSON Server is running at http://localhost:3000/')
});
if I have a request like http://localhost:3000/users?firstName_like=l&_limit=10&_page=2, inside the render callback fn, only firsName_like is persisted. The rest, _limit and _page is gone.
In addition, if I have a request like http://localhost:3000/users?firstName_like=l, the _limit modification on the middleware works and I receive a response with the corresponding default limit of 10 records. But it also does not show in the render callback fn.