我正在使用 json-server 为前端团队伪造 Api。
我们希望有一个功能可以在一次调用中创建多个对象(例如产品)。
在WebApi2或实际的RestApis中,可以像下面这样完成:
POST api/products //For Single Creation
POST api/productCollections //For Multiple Creation
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用 json-server 来实现它。api/products我尝试使用邮递员将以下数据发布到,但它不会拆分数组并单独创建项目。
[
{
"id": "ff00feb6-b1f7-4bb0-b09c-7b88d984625d",
"code": "MM",
"name": "Product 2"
},
{
"id": "1f4492ab-85eb-4b2f-897a-a2a2b69b43a5",
"code": "MK",
"name": "Product 3"
}
]
Run Code Online (Sandbox Code Playgroud)
它将整个数组视为单个项目并附加到现有的 json。
您能否建议我如何在 json-server 中模拟批量插入?或者 Restful Api 应该始终用于单个对象操作?
小智 5
据我所知,这不是 json-server 本身支持的东西,但可以通过解决方法来完成。
我假设您对 Node.js 有一些先验知识
您必须创建一个 server.js 文件,然后使用 node.js 运行该文件。然后,server.js 文件将使用 json-server 模块。
我已将 server.js 文件的代码包含在下面的代码片段中。
我使用 lodash 进行重复检查。因此,您需要安装 lodash。如果您不想使用 lodash,您也可以将其替换为您自己的代码,但我认为 lodash 工作得很好。
server.js 文件包含一个自定义 post 请求函数,该函数访问 json-server 实例中使用的 lowdb 实例。检查来自 POST 请求的数据是否有重复项,并且仅将新记录添加到 ID 尚不存在的数据库中。lowdb的write()函数将数据持久化到db.json文件中。因此,内存中的数据和文件中的数据将始终匹配。
请注意,由 json-server 生成的 API 端点(或重写的端点)仍然存在。因此,您可以将自定义函数与默认端点结合使用。
请随意在需要时添加错误处理。
const jsonServer = require('json-server');
const server = jsonServer.create();
const _ = require('lodash')
const router = jsonServer.router('./db.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;
server.use(middlewares);
server.use(jsonServer.bodyParser)
server.use(jsonServer.rewriter({
'/api/products': '/products'
}));
server.post('/api/productcollection', (req, res) => {
const db = router.db; // Assign the lowdb instance
if (Array.isArray(req.body)) {
req.body.forEach(element => {
insert(db, 'products', element); // Add a post
});
}
else {
insert(db, 'products', req.body); // Add a post
}
res.sendStatus(200)
/**
* Checks whether the id of the new data already exists in the DB
* @param {*} db - DB object
* @param {String} collection - Name of the array / collection in the DB / JSON file
* @param {*} data - New record
*/
function insert(db, collection, data) {
const table = db.get(collection);
if (_.isEmpty(table.find(data).value())) {
table.push(data).write();
}
}
});
server.use(router);
server.listen(port);
Run Code Online (Sandbox Code Playgroud)
如果你有任何问题随时问。
| 归档时间: |
|
| 查看次数: |
12499 次 |
| 最近记录: |