expressjson-server

Syntax for json-server middlewares


I am trying to use middleware in json-server, just to append specific properties to body response at specific routes. I have this working code:

server.use(jsonServer.bodyParser);
server.use((req, res, next) => {
  switch (req.path) {
    case '/items':
      switch (req.method){
        case 'POST':
          req.body.dateCreated = Date.now();
          req.body.status = 0;
          break;

        case 'PUT':
          req.body.dateModified = Date.now();
          break;
      }
  }
  next();
});

server.use(router);

but I was wondering if there is a nicer syntax/way to install these overrides the express-way, ie. server.method(path, cb) - something like:

app.post('/items', (req, res, next) => {
  // my override
});

so that route parameters (such as items/:id) can be easily resolved?


Solution

  • For anyone having this issue, it seems that the router that json-server returns to you is an Express router (so you can apply similar patterns as Express middleware).

    For example:

    server.use("/items", require("./customMiddleware1")); // all requests to /items
    server.post("/items", require("./customMiddleware2")); // post requests to /items
    
    server.use("/users", require("./customMiddleware3")); // all requests to /users
    

    And then create the files for your middleware. For example, customMiddleware2.js:

    function customMiddleware2(req, res, next) {
        console.log("that was a post request!");
        next();
    }
    
    module.exports = customMiddleware2;
    

    You may also find this answer useful: https://stackoverflow.com/a/49562328/11298742