我正在使用json-server为FrontEnd团队伪造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应该总是用于单对象操作?
发布于 2019-09-11 23:44:27
据我所知,json-server本身并不支持这一点,但可以通过一种变通方法来实现。
我假设您对node.js有一定的先验知识
您必须创建一个server.js文件,然后使用node.js运行该文件。然后,server.js文件将使用json-server模块。
我已经在下面的代码片段中包含了server.js文件的代码。
我用罗达什做我的复印件。因此,您将需要安装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);如果您有任何问题,请随时提出。
发布于 2020-07-06 18:36:31
被标记为正确的答案实际上对我并不起作用。由于插入函数的编写方式,它将始终生成新文档,而不是更新现有文档。“重写”对我也不起作用(也许我做错了什么),但创建一个完全独立的端点很有帮助。
这是我的代码,以防其他人尝试执行批量插入(以及修改现有数据(如果存在))。
const jsonServer = require('json-server');
const server = jsonServer.create()
const _ = require('lodash');
const router = jsonServer.router('./db.json');
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
server.post('/addtasks', (req, res) => {
const db = router.db; // Assign the lowdb instance
if (Array.isArray(req.body)) {
req.body.forEach(element => {
insert(db, 'tasks', element);
});
}
else {
insert(db, 'tasks', req.body);
}
res.sendStatus(200)
function insert(db, collection, data) {
const table = db.get(collection);
// Create a new doc if this ID does not exist
if (_.isEmpty(table.find({_id: data._id}).value())) {
table.push(data).write();
}
else{
// Update the existing data
table.find({_id: data._id})
.assign(_.omit(data, ['_id']))
.write();
}
}
});
server.use(router)
server.listen(3100, () => {
console.log('JSON Server is running')
})在前端,调用将如下所示:axios.post('http://localhost:3100/addtasks', tasks)
发布于 2020-09-02 18:03:49
当这个问题发布时,它可能不工作,但是现在它工作了,使用/products端点上的一个数组调用以进行大容量插入。
https://stackoverflow.com/questions/57868537
复制相似问题