一般情況下,一個雲函數完成單一的邏輯功能,就是一個類的方法一樣,如圖:
但是受限免費用戶最多隻能使用20個雲函數,想要在單一雲函數中實現多個複雜的功能就需要通過參數來區別,可讀性差,不利於管理。通過路由,嘗試將請求歸類,一個雲函數處理某一類的請求,比如有專門負責處理用戶的,或者專門處理支付的雲函數。如圖:
爲了方便大家試用,騰訊雲 Tencent Cloud Base 團隊開發了 tcb-router,雲函數路由管理庫方便大家使用。
基於 koa 風格的小程序·雲開發雲函數輕量級類路由庫,主要用於優化服務端函數處理邏輯
使用
npm install --save tcb-router
雲函數端
// 雲函數的 index.js
const TcbRouter = require('./router');
exports.main = (event, context) => {
const app = new TcbRouter({ event });
// app.use 表示該中間件會適用於所有的路由
app.use(async (ctx, next) => {
ctx.data = {};
await next(); // 執行下一中間件
});
// 路由爲數組表示,該中間件適用於 user 和 timer 兩個路由
app.router(['user', 'timer'], async (ctx, next) => {
ctx.data.company = 'Tencent';
await next(); // 執行下一中間件
});
// 路由爲字符串,該中間件只適用於 user 路由
app.router('user', async (ctx, next) => {
ctx.data.name = 'heyli';
await next(); // 執行下一中間件
}, async (ctx, next) => {
ctx.data.sex = 'male';
await next(); // 執行下一中間件
}, async (ctx) => {
ctx.data.city = 'Foshan';
// ctx.body 返回數據到小程序端
ctx.body = { code: 0, data: ctx.data};
});
// 路由爲字符串,該中間件只適用於 timer 路由
app.router('timer', async (ctx, next) => {
ctx.data.name = 'flytam';
await next(); // 執行下一中間件
}, async (ctx, next) => {
ctx.data.sex = await new Promise(resolve => {
// 等待500ms,再執行下一中間件
setTimeout(() => {
resolve('male');
}, 500);
});
await next(); // 執行下一中間件
}, async (ctx)=> {
ctx.data.city = 'Taishan';
// ctx.body 返回數據到小程序端
ctx.body = { code: 0, data: ctx.data };
});
return app.serve();
}
tips: 小程序雲函數的 node 環境默認支持 async/await 語法,推薦涉及到的異步操作時像 demo 中那樣使用
小程序端
// 調用名爲 router 的雲函數,路由名爲 user
wx.cloud.callFunction({
// 要調用的雲函數名稱
name: "router",
// 傳遞給雲函數的參數
data: {
$url: "user", // 要調用的路由的路徑,傳入準確路徑或者通配符*
other: "xxx"
}
});
完整的實例,請參考我的另一篇博客: 分享使用tcb-router路由開發的雲函數短信平臺SDK請添加鏈接描述