tcbRouter

tcb-router

基于koa风格的小程序·云开发云函数轻量级类路由库,主要用于优化服务端函数处理逻辑

安装

云函数当前目录下安装:npm install --save tcb-router

 

 

 使用

const tcbRouter = require('tcb-router');
exports.main = async (event, context) => {
  const app = new tcbRouter({ event });  //event对象中包含了请求的所有参数(包括$url)   +     userInfo(  appId(小程序)+openId(用户的)   )
 
  //路由1--detail ($url=='detail'
    //获取博客详情
    app.router('detail', async (ctx, next)=>{
      //可获取请求中的参数
      let blogId = event.blogId;
      //通过赋值给ctx.body来返回响应结果
       ctx.body = XXXX;
    })
 
  //路由2
  。。。
 
  //路由3
  。。。
  return app.serve(); // 必须以此句结束
})

event对象

event 指的是触发云函数的事件,当小程序端调用云函数时,event 就是小程序端调用云函数时传入的参数,外加后端自动注入的小程序用户的 openid 和小程序的 appid。

总结:event对象中包含了请求的所有参数   +   userInfo(  appId(小程序)+ openId(用户的)   )

测试:

客户端代码

//获取博客列表

_loadBlogList(start = 0){
  // 显示加载提示
  wx.showLoading({
    title: '加载中',
  })
  wx.cloud.callFunction({
    name:'blog',//云函数目录名称
  data:{
    keyword,
    $url:'list',
    start: start,
    count:10
  }
  }).then((res)=>{
    console.log("_loadBlogList suc", res)
    this.setData({
    blogList:this.data.blogList.concat(res.result)
  })
  // 隐藏加载提示
  wx.hideLoading()
  }).catch((err)=>{
    // 隐藏加载提示
    console.error(err)
  })
}
 
云函数

event, { '$url': 'list',

count: 10,

keyword: '',

start: 0,

userInfo:

{ appId: '。。。',

openId: '。。。' } }

//对比发现,event对象中包含了请求的所有参数   +   userInfo(  appId(小程序)+openId(用户的)   )

 

context对象

context 对象包含了此处调用的调用信息和运行状态,可以用它来了解服务运行的情况。

 

context, { callbackWaitsForEmptyEventLoop: [Getter/Setter],

 

done: [Function: done],

 

succeed: [Function: succeed],

 

fail: [Function: fail],

 

getRemainingTimeInMillis: [Function: getRemainingTimeInMillis],

 

memory_limit_in_mb: 256,//字节限制

 

time_limit_in_ms: 3000,//时间限制

 

request_id: 'eaf169f6-16ef-11ea-9cfd-5254002fa145',//请求id

 

environ: xxx(内容有点长),//环境

 

function_version: '$LATEST',//云函数版本

 

function_name: 'blog',//云函数名称

 

namespace: 'env1-bxl-1' }//域名空间(环境id)

 

posted @ 2019-12-05 07:58  baixinL  阅读(737)  评论(0编辑  收藏  举报