rest - POST json-server 中的对象集合
问题描述
我正在使用 json-server 为前端团队伪造 Api。
我们希望有一个功能可以在一次调用中创建多个对象(例如产品)。
在 WebApi2 或实际的 RestApis 中,可以这样做:
POST api/products //For Single Creation
POST api/productCollections //For Multiple Creation
我不知道如何使用 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"
}
]
它将整个数组视为单个项目并附加到现有的 json。
您能否建议我如何在 json-server 中模拟批量插入?还是 Restful Api 应该始终用于单个对象操作?
解决方案
据我所知,这不是 json-server 本身支持的东西,但可以通过解决方法来完成。
我假设您对 node.js 有一些先验知识
您将必须创建一个 server.js 文件,然后您将使用 node.js 运行该文件。server.js 文件将使用 json-server 模块。
我在下面的代码片段中包含了 server.js 文件的代码。
我使用 lodash 进行重复检查。因此,您将需要安装 lodash。如果您不想使用 lodash,也可以将其替换为您自己的代码,但我认为 lodash 工作得很好。
server.js 文件包含一个自定义发布请求函数,该函数访问 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);
如果您有任何问题随时问。
推荐阅读
- oracle - 如何处理 ssis 表达式中的 oracle regexp_like
- python-3.x - 用户输入不延迟程序
- scala - sbt无法同步项目,因为无法编译
- r - 过滤掉指定日期范围内的 ID
- java - Java String.contains 与 String.contentEquals
- java - 转换列表
- xamarin - 如果初始状态不可见,SearchBar 会更改颜色
- php - 如何更改网络超级管理员 WordPress 的默认用户名?
- selenium - 当相同的简单选择器在 chrome 控制台中工作时,为什么我会收到无效的选择异常?
- javascript - 排序矩阵AngularJS