简体   繁体   English

如何使用 json-server 将模拟 API 调用保存到 2 个地方?

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

I am using json-server to mock my REST API during testing.我在测试期间使用 json-server 来模拟我的 REST API。

It works fine for POST and GET of the same data.它适用于相同数据的 POST 和 GET。 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.这意味着当我执行 POST 时,它需要保存要由关联的 GET 检索的数据,但也需要在不同的 API 调用中从 GET 检索。

How do I configure json-server to save the POST data in 2 different parts of the db.json?如何配置 json-server 以将 POST 数据保存在 db.json 的 2 个不同部分?

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 .如果您使用默认方法运行它,它只会将 POST 保存在db.json的相关部分中。

However, if you can also run it with express to customise it.但是,如果您也可以使用 express 运行它来自定义它。

"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.然后,这允许您在index.js中编写 javascript 以获取db.json的内容并将数据作为其他 POST 的一部分推送到审计部分。 eg例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM