zoukankan      html  css  js  c++  java
  • 配置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 }
  • 相关阅读:
    从远程仓库更新本地仓库
    git添加所有新文件
    删除远程仓库文件夹
    更新被驳回
    git安装和第一次提交过程
    JSONobject按照put顺序存储和读取
    Map 转 json格式 保留null值的解决办法
    Java对象转换Json的细节处理
    如何解析json格式的字符串
    json 拼装空list、object
  • 原文地址:https://www.cnblogs.com/galaxy2490781718/p/13232598.html
Copyright © 2011-2022 走看看