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 }
  • 相关阅读:
    H5实现查看图片和删除图片的效果
    HTTP 状态码(HTTP Status Code)
    HashMap详解(基于JDK 1.8)
    FutureTask详解
    ForkJoin框架详解
    final详解
    磁盘管理之inode与block
    如何在CentOS上安装一个2048小游戏
    Linux帮助手册(man)
    Linux入门-基础命令
  • 原文地址:https://www.cnblogs.com/galaxy2490781718/p/13232598.html
Copyright © 2011-2022 走看看