Files
koa-router/README.md
2024-10-11 17:04:41 +08:00

71 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# koa-router
KOA路由中间件
## 安装
```
npm install @yizhi/koa-router
```
## 使用
```typescript
import Koa from 'koa';
import Router from '@yizhi/koa-router';
const app = new Koa();
const router = new Router();
router.get("/path/to/get", async (ctx, next) => {
// do something
});
app.use(router.callback());
```
## 路径参数
路径参数使用"{name}"或"{name:type}"来表示系统默认支持int、boolean两种类型当不指定类型时表示字符串类型。
也可以根据自身需要扩展自己的类型。
### 1、基本使用
系统默认只支持字符串类型参数如果需要启用int和boolean类型参数可以通过选项`defaultParamTypes`来设置,也可以通过方法`installDefaultParamTypes`来设置。
```typescript
const router = new Router({ defaultParamTypes: true });
// 匹配 "/api/user/123" "/api/user/abc"
router.get("/api/user/{id}", async (ctx, next) => {});
// 匹配 "/api/user/123"
router.get("/api/user/{id:int}", async (ctx, next) => {});
```
### 2、自定义类型
自定义参数类型可以通过选项`customParamtypes`和方法`installCustomParamType`来设置。
```typescript
const router = new Router({ defaultParamTypes: true });
//uuid类型
router.installParamType("uuid", /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/);
// date类型匹配结果转换为{year, month, day}格式的对象
router.installParamType("date", /\d{4}-\d{2}-\d{2}/, (value) => {
const [year, month, day] = value.spliet("-").map(parseInt);
return { year, month, day };
});
// 匹配 "/api/user/12345678-1234-1234567890ab"
router.get("/api/user/{id:uuid}", async (ctx, next) => {
console.log(ctx.params.id); // 输出 "12345678-1234-1234567890ab"
});
//匹配 "/api/logs/2021-10-01"
router.get("/api/logs/{date:date}", async (ctx, next) => {
console.log(ctx.params.date); // 输出 {year: 2021, month: 10, day: 1}
});
```