- 一个用户在一个云环境中只能创建50个云函数
- 相似的请求归类到同一个云函数处理
- tcb-router是一个koa风格的云函数路由库
koa洋葱模型
tcb-router:基于 koa 风格的小程序·云开发云函数轻量级类路由库,主要用于优化服务端函数处理逻辑
云函数端使用
新建tcbrouter云函数
右键-在云端中打开
安装tcb-router:
npm install --save tcb-router
新建名为tcbrouter的云函数
在其js文件中添加如下代码:
// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router')
cloud.init()
// 云函数入口函数
exports.main = async(event, context) => {
const app = new TcbRouter({
event
})
app.use(async(ctx, next) => {
console.log('进入全局中间件')
ctx.data = {}
ctx.data.openId = event.userInfo.openId
await next()
console.log('退出全局中间件')
})
app.router('music', async(ctx, next) => {
console.log('进入音乐名称中间件')
ctx.data.musicName = '光年之外'
await next()
console.log('退出音乐名称中间件')
}, async(ctx, next) => {
console.log('进入音乐类型中间件')
ctx.data.musicType = '华语歌曲'
ctx.body = {
data: ctx.data
}
console.log('退出音乐类型中间件')
})
app.router('movie', async(ctx, next) => {
console.log('进入电影名称中间件')
ctx.data.movieName = '肖申克的救赎'
await next()
console.log('退出电影名称中间件')
}, async(ctx, next) => {
console.log('进入电影类型中间件')
ctx.data.movieType = '美国电影'
ctx.body = {
data: ctx.data
}
console.log('退出电影类型中间件')
})
return app.serve()
}
编写完后,上传云函数。
demo.wxml中添加两个按钮
<button bind:tap="getMusicInfo">获取音乐信息</button>
<button bind:tap="getMovieInfo">获取电影信息</button>
demo.js中添加两个方法
getMusicInfo() {
wx.cloud.callFunction({
name: 'tcbrouter',
data: {
$url: 'music'
},
}).then((res) => {
console.log(res)
})
},
getMovieInfo() {
wx.cloud.callFunction({
name: 'tcbrouter',
data: {
$url: 'movie'
}
}).then((res) => {
console.log(res)
})
},
点击两个按钮,分别打印一下信息,说明路由设置成功
查看云函数的日志,如下图: