配置CRUD通用接口

 1 module.exports = app => {
 2   const router = require('express').Router({
 3     mergeParams: true
 4   })
 5 
 6   //
 7   router.post('/', async (req, res) => {
 8     await req.Model.create(req.body)
 9     res.send({
10       success: true
11     })
12   })
13   // 根据ID删除
14   router.delete('/:id', async (req, res) => {
15     await req.Model.findByIdAndDelete(req.params.id)
16     res.send({
17       success: true
18     })
19   })
20   // 根据ID修改
21   router.put('/:id', async (req, res) => {
22     await req.Model.findByIdAndUpdate(req.params.id, req.body)
23     res.send({
24       success: true
25     })
26   })
27   //
28   router.get('/', async (req, res) => {
29     const queryOptions = {}
30     if (req.Model.modelName === 'Category') {
31       queryOptions.populate = 'parent'
32     }37     const data = await req.Model.find().setOptions(queryOptions)
38     res.send(data)
39   })
40   // 根据ID查询
41   router.get('/:id', async (req, res) => {
42     const data = await req.Model.findById(req.params.id)
43     res.send(data)
44   })
45 
46   app.use('/admin/api/rest/:resource', async (req, res, next) => {
47     const classify = require('inflection').classify // 小写复数形式转换为首字母大写单数形式的类名
48     req.Model = require(`../models/${classify(req.params.resource)}`)
49     next()
50   }, router)
51 }
原文地址:https://www.cnblogs.com/galaxy2490781718/p/13232598.html