# cmd-cloud-router **Repository Path**: TsMask/cmd-cloud-router ## Basic Information - **Project Name**: cmd-cloud-router - **Description**: 【rollup】基于洋葱圈模型的云函数路由库,编写类 RESTful 资源路由 - **Primary Language**: TypeScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 3 - **Forks**: 0 - **Created**: 2022-06-24 - **Last Updated**: 2025-09-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: uni-app, 云函数 ## README # cmd-cloud-router > 基于洋葱圈模型的云函数路由库,编写类 RESTful 资源路由 ## 介绍 简易 `koa` 洋葱圈模型执行,`koa-router` 路由风格编写云函数。 - 每个云函数是一个独立进程,使用路由分为多部分 - 使用 `path-to-regexp` 函数库解析路由参数 `/user/:bar/:foo` - 函数需要使用 `nodejs16` 版本以上, 中间件使用 `Promise` 函数。 ## 函数-API ### 应用对象(Application) `Application` 是请求级别的全局应用对象,监听云函数执行。基于洋葱圈模型,请求从第一个中间件开始并按其方式顺序运行。 | 函数 | 名称 | 说明 | | :------- | :----------- | :--------------------------------- | | use | 注册使用中间件 | 使用给定中间件加入程序执行过程 | | listen | 监听程序请求 | 将云函数请求数据加入到应用程序对象 | 客户端调用云函数时传入的参数数据 | 参数 | 说明 | | :------- | :------------------------------------ | | url | 必传参数,请求已定义的路由路径 | | method | 可选参数,路由路径指定的请求方法,默认GET方法 | | data | 可选参数,传入可能需要的参数数据 | 使用示例: ```js const { Application } = require("cmd-cloud-router"); const app = new Application(); // 使用中间件,请使用异步函数保证执行顺序 app.use(async (ctx, next) => { console.time("计时"); let sum = 0; for (let i = 0; i < 99; i++) { for (let j = 0; j < i; j++) { sum += j; } } await next(); // 响应结果要用 ctx.body ctx.body = `求和:${sum}`; console.timeEnd("计时"); }); // 客户端调用云函数时传入的参数 const event = { url: "/add", method: "post", data: { value: 99 }, }; // 客户端调用云函数时的系统运行环境参数 const context = { text: "云函数请求环境", SOURCE: "云函数调用来源", }; // 传入全局配置 const config = { name: "测试配置", value: "1.0.0", }; // 对请求参数监听 返回Promise对象 app.listen(event, context, config).then(res => { console.log("响应ctx.body的结果:", res); }) .catch(err => { console.log("错误结果:", err); }); ``` #### 上下文 Context `Context` 是请求级别的对象,封装了请求的信息,对每一次请求都会重新初始上下文参数属性。 请求上下文对象信息: | 取值 | 说明 | 类型 | | :------- | :----------- | :--------------------------------- | | event | 客户端调用云函数时传入的参数 | object | | app | 客户端调用云函数时的系统运行环境参数 | object | | url | 请求资源 | string | | method | 请求方法 | string | | data | 请求参数 | object | | path | url路径 | string | | querystring | url查询字符串 | string | | query | url查询参数 | object | | params | url路由参数 | object | | body | 程序执行后通过该属性返回结果,函数内 `return` 是没有效果的 | object | | config | 可选的传入全局配置参数 | object | | * | 可选的中间件进行属性参数传递 | 任意值 | #### 中间件 Middleware `Middleware` 是请求级别的函数,在程序执行过程前或后加入处理逻辑,实现程序拦截过滤等功能。 ```js module.exports = async (ctx, next) => { console.time("logger"); // 定义属性参数 ctx.logger = "日志中间件"; // 中间件放行 await next(); console.timeEnd("logger"); }; ``` 1. 如果没有触发`next()`函数,会终止程序并返回上下文 `body` 属性的结果。 2. 确保执行结果符合洋葱模型,请使用 `Promise` 对象的函数。 3. 上下文可以定义属性参数,数据生命周期只存在当前请求。 ### 路由对象(Router) `Router` 路由命名 URL 路由规则风格,支持 http 方法声明路由,可以只针对单个路由使用中间件,处理每一次请求。 | 函数 | 名称 | 说明 | | :--------- | :----------- | :------------------------- | | prefix | 路由前缀 | 统一定义路由前缀 | | register | 注册路由 | 创建并注册路由路径 | | get | GET路由请求 | 注册指定的get请求方法路由路径 | | post | POST路由请求 | 注册指定的post请求方法路由路径 | | put | PUT路由请求 | 注册指定的put请求方法路由路径 | | delete | DELETE路由请求 | 注册指定的delete请求方法路由路径 | | routes | 路由表中间件函数 | 添加到应用对象中,执行请求匹配的路由函数 | 云函数调用来源为 `timing` 定时触发器会将 `cron` 表达式转换为 `PUT` 方法路由(hex 编码化) 转换例如 `cron:0 0 * * * *` => `63726f6e3a302030202a202a202a202a` 使用示例: ```js const { Router } = require("cmd-cloud-router"); const router = new Router(); // 使用指定方法路由 // router.["get" | "post" | "put" | "delete"](, <函数>, <其他参数>); router.post( "/index", async ctx => { ctx.body = "成功"; }, { middleware: [ async (ctx, next) => { await next(); }, ] } ); // 使用自定义方法路由 // router.register(<请求方法>, , <函数>, <其他参数>); router.register( "post", "/index", async ctx => { ctx.body = "成功"; }, { middleware: [ async (ctx, next) => { await next(); }, ] } ); // 云函数调用来源为 timing 定时cron表达式转换路由 hex编码化 const cronPath = Buffer.from("cron:0 0 * * * *", "utf-8").toString("hex"); router.put(cronPath, async ctx => { console.log("执行 ==> %s - %s <==", ctx.method, ctx.path); // 定时任务没有需要响应的 ctx.body }); // 注册到应用对象中间件中使用 // app.user(router.routes()); ``` ## 注解-API - 路由控制器:Controller - 路由方法:RequestMapping, Get, Post, Put, Del 将控制器声明的Class类文件进行扫描加入路由:ScanController 声明注解需要在[TS编译](https://gitee.com/TsMask/cloud-router-demo)环境下支持,已在使用 `vite + ts` 方式进行打包部署测试。 ## 鸣谢 - 参考 [koa](https://github.com/koajs/koa) - 参考 [koa-router](https://github.com/koajs/router) - 参考 [koa-compose](https://github.com/koajs/compose) - 使用 [uniCloud 云函数](https://doc.dcloud.net.cn/uniCloud/cf-functions.html)