增删改查

2021-04-17  本文已影响0人  波仔_4867

前端

使用路由安装 cnpm i tcb-router -S

// 添加商品
    addProduct(){
        let data={
            info:'容克大妈',
            address:'法国',
            $url:'add'
        }
        wx.cloud.callFunction({
            name:'product',
            data,
        }).then(res=>{
            console.log(res);
        })
    },
    // 查询商品
    selectProduct(){
        let id='e050b1a6606ffaf300718e6977e4c016'
        wx.cloud.callFunction({
            name:'product',
            data:{
                _id: id,
                $url: 'get'
            }
        }).then(res=>{
            console.log(res);
        })
    },
    // 更新商品
    updateProduct(){
        let id='e050b1a6606ffaf300718e681912c70b'
        wx.cloud.callFunction({
            name:'product',
            data:{
                _id: id,
                info: '容克大妈',
                $url:'update'
            }
        }).then(res=>{
            console.log(res);
        })
    },
    // 删除商品
    delProduct(){
        let id='e050b1a6606ffaf300718e681912c70b'
        wx.cloud.callFunction({
            name:'product',
            data: {
                _id: id,
                $url:'del'
               },
        }).then(res=>{
            console.log(res);
        })

    }

后端

// 云函数入口文件
const cloud = require('wx-server-sdk')
// 引入路由模块
const TcbRouter = require('tcb-router')
cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
     // 创建路由实例
  const app = new TcbRouter({
    // 把event对象注入到路由中间件,在中间件中随时可以调用event
    event
  })
// 添加记录的路由
// add为自定义路由名称
app.router('add', async (ctx, next) => {
    //可以直接调用event
    ctx.body = await db.collection('product').add({
        data: {
          info: event.info,
          address: event.address,
        }
      })
      .then((res) => {
        return res
      })
  })
 // 获取所有商品信息
app.router('getAll', async (ctx, next) => {
  ctx.body = await db.collection('product').get()
    .then((res) => {
      return res
    })
})
// 获取指定商品信息
app.router('get', async (ctx, next) => {
  let _id = event._id
  ctx.body = await db.collection('product').where({
    _id
  }).get()
    .then((res) => {
      return res
    })
})
// 更新商品信息
app.router('update', async (ctx, next) => {
  let _id = event._id
  ctx.body = await db.collection('product').where({
    _id: event._id
  }).update({
    data:{
      info: event.info
    }
  })
    .then((res) => {
      return res
    })
})
// 删除商品信息
app.router('del', async (ctx, next) => {
  ctx.body = await db.collection('product').where({
    _id: event._id
  }).remove()
    .then((res) => {
      return res
    })
})
    return app.serve()
}
上一篇下一篇

猜你喜欢

热点阅读