小程序云函数的高级玩法-路由

一般情况下,一个云函数完成单一的逻辑功能,就是一个类的方法一样,如图:

小程序云函数的高级玩法-路由

但是受限免费用户最多只能使用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请添加链接描述

猜你喜欢

转载自blog.51cto.com/7174555/2382028
今日推荐