How Do I Save A Mock API Call To 2 Places Using json-server?

341 views Asked by At

I am using json-server to mock my REST API during testing.

It works fine for POST and GET of the same data. However, I have a requirement to save an audit trail.

This means when I do a POST it needs to save the data to be retrieved by the associated GET but it also needs to be retrieved from the GET in a different API call.

How do I configure json-server to save the POST data in 2 different parts of the db.json?

1

There are 1 answers

0
opticyclic On

The first part is how you run it. If you run it with the default method it just saves the POST in the relevant section of the db.json.

However, if you can also run it with express to customise it.

"scripts": {
  "start": "node index.js",
  "start-dev": "nodemon index.js",
},

This then allows you to write javascript in the index.js that gets the contents of the db.json and push the data into the audit section as part of the other POST. e.g.

server.post("/data/create", (req, res) => {
  var decodedObj = jwt_decode(req.headers.jwt);
  let db = router.db;

  db.get("audit")
    .push({
      ...req.body,
      status: "New",
      user: decodedObj.name,
    })
    .write();

  const data = db.get("data").value();

  return res.json({
    status: 201,
    data: data[data.length - 1],
  });
});