作用
-
路由分发:根据请求路径和方法,将请求分发到不同的处理函数。
-
简化代码:减少重复代码,提高代码可读性和可维护性。
-
中间件支持:支持中间件机制,可以在请求处理前后执行一些通用逻辑。
优势
特性 | 原始写法 | tcb-router 写法 |
---|---|---|
代码结构 | 嵌套的 if-else ,难以维护 | 路由表形式,结构清晰 |
中间件支持 | 需要手动重复编写 | 支持中间件,代码复用 |
参数解析 | 手动解析路径和查询参数 | 自动解析路径和查询参数 |
错误处理 | 每个分支单独处理 | 全局错误处理 |
异步支持 | 需要手动处理 Promise | 天然支持 async/await |
扩展性 | 较差 | 良好 |
安装
在使用 tcb-router
之前,确保你已经安装了 tcb-router
包。可以通过 npm 安装:
npm install tcb-router
基本语法
1. 引入 tcb-router
首先,你需要在云函数中引入 tcb-router
:
const TcbRouter = require('tcb-router');
2. 创建 tcb-router
实例
在云函数中创建一个 tcb-router
实例:
exports.main = async (event, context) => {
const app = new TcbRouter({ event });
// 在这里定义路由和处理函数
return app.serve();
};
3. 定义路由
你可以使用 app.router
方法来定义路由。路由可以根据请求方法和路径进行匹配。
app.router('GET /user', async (ctx, next) => {
// 处理 GET /user 请求
ctx.body = { message: '获取用户信息' };
});
app.router('POST /user', async (ctx, next) => {
// 处理 POST /user 请求
ctx.body = { message: '创建用户' };
});
4. 中间件
tcb-router
支持中间件机制,可以在请求处理前后执行一些通用逻辑。
app.use(async (ctx, next) => {
// 在路由处理之前执行的逻辑
console.log('请求开始');
await next();
// 在路由处理之后执行的逻辑
console.log('请求结束');
});
app.router('GET /user', async (ctx, next) => {
ctx.body = { message: '获取用户信息' };
});
5. 处理请求参数
你可以通过 ctx.event
访问请求参数:
app.router('GET /user/:id', async (ctx, next) => {
const userId = ctx.event.pathParameters.id;
ctx.body = { message: `获取用户ID为 ${userId} 的信息` };
});
6. 返回响应
通过 ctx.body
设置响应内容:
app.router('GET /user', async (ctx, next) => {
ctx.body = { message: '获取用户信息' };
});
完整示例
const TcbRouter = require('tcb-router');
exports.main = async (event, context) => {
const app = new TcbRouter({ event });
// 中间件
app.use(async (ctx, next) => {
console.log('请求开始');
await next();
console.log('请求结束');
});
// 定义路由
app.router('GET /user', async (ctx, next) => {
ctx.body = { message: '获取用户信息' };
});
app.router('POST /user', async (ctx, next) => {
ctx.body = { message: '创建用户' };
});
app.router('GET /user/:id', async (ctx, next) => {
const userId = ctx.event.pathParameters.id;
ctx.body = { message: `获取用户ID为 ${userId} 的信息` };
});
return app.serve();
};