笔记来源:小程序·云开发 — 云函数项目实战
文档 tcb-router
云函数 index.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 表示该中间件会适用于所有的路由
app.use(async (ctx, next) => {
console.log('---------->进入全局的中间件')
ctx.data = {};
ctx.data.openId = event.userInfo.openId
await next(); // 执行下一中间件
console.log('---------->退出全局的中间件')
});
// 路由为数组表示,该中间件适用于 user 和 school 两个路由
app.router(['user', 'school'], async (ctx, next) => {
console.log('---------->进入数组路由中间件')
ctx.data.from = '小程序云函数实战'
await next(); // 执行下一中间件
console.log('---------->退出数组路由中间件')
});
// 路由为字符串,该中间件只适用于 user 路由
app.router('user', async (ctx, next) => {
console.log('---------->进入用户路由中间件')
ctx.data.name = 'xiaoqiang user';
ctx.data.role = 'Developer'
await next();
console.log('---------->退出用户路由中间件')
},async (ctx) => {
console.log('---------->进入用户昵称路由中间件')
ctx.data.nickName = 'BestTony'
ctx.body = { code: 0, data: ctx.data }; // 将数据返回给云函数,用ctx.body
console.log('---------->退出用户昵称路由中间件')
});
app.router('school', async (ctx, next) => {
ctx.data.name = '腾讯云学院';
ctx.data.url = 'cloud.tencent.com'
await next();
}, async (ctx) => {
ctx.data.nickName = '学院君'
ctx.body = { code: 0, data: ctx.data }; // 将数据返回给云函数,用ctx.body
});
return app.serve();
}
小程序端
Page({
school: function(event){
// 调用名为 tcbRouter 的云函数,路由名为 school
wx.cloud.callFunction({
// 要调用的云函数名称
name: "tcbRouter",
// 传递给云函数的参数
data: {
$url: "school", // 要调用的路由的路径,传入准确路径或者通配符*
other: "xxx"
}
}).then(res => {
console.log(res)
});
},
user: function (event) {
// 调用名为 tcbRouter 的云函数,路由名为 user
wx.cloud.callFunction({
// 要调用的云函数名称
name: "tcbRouter",
// 传递给云函数的参数
data: {
$url: "user", // 要调用的路由的路径,传入准确路径或者通配符*
other: "xxx"
}
}).then(res => {
console.log(res)
});
}
})
触发 user 事件后,云开发控制台 tcbRouter 云函数日志记录输出如下:
---------->进入全局的中间件
---------->进入数组路由中间件
---------->进入用户路由中间件
---------->进入用户昵称路由中间件
---------->退出用户昵称路由中间件
---------->退出用户路由中间件
---------->退出数组路由中间件
---------->退出全局的中间件