UNPKG

@zenweb/router

Version:

Zenweb Router module

72 lines (53 loc) 2.43 kB
# AGENTS.md AI 专用 API 文档,随 npm 包发布。 ## 导出 **默认导出**: `setup(opt?: { prefix?: string })` — ZenWeb 安装函数,注入 `app.router``ctx.params``ctx.router`**类**: `Router` **类型**: - `RouterPath = string | RegExp | (string | RegExp)[]` - `RouterMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'LINK' | 'UNLINK' | 'ALL'` - `RouterParams = Record<string, string>` - `RouterMatch = { params: RouterParams; handler: Middleware }` - `RouterOptions = { prefix?: string }` - `RouterRegisterOption = { prefix?: string; path: RouterPath; method: RouterMethod | RouterMethod[]; middleware: Middleware | Middleware[] }` ## Router 方法 | 方法 | 签名 | |------|------| | `register` | `(opt: { prefix?, path, method, middleware }) => this` | | `get/post/put/patch/delete` | `(path: RouterPath, ...middleware) => this` | | `all` | `(path: RouterPath, ...middleware) => this` | | `use` | `(...middlewares) => this` | | `add` | `(...routers: Router[]) => this` | | `match` | `(path: string, method?: string) => RouterMatch \| undefined` | | `matchSelf` | `(path: string, method: RouterMethod) => RouterMatch \| undefined` | | `server` | `() => Middleware` | | `getCount` | `() => { statics, params, wildcards, regexs, subRouters }` | > `HEAD/OPTIONS/LINK/UNLINK` 方法需通过 `register` 注册。 ## 路径语法 路径参数提取到 `ctx.params` 对象。 | 类型 | 示例 | ctx.params | |------|------|------------| | 静态 | `/api/users` | `{}` | | 参数 | `/user/:id` | `{ id: "123" }` | | 前缀参数 | `/file:name.ext` | `{ name: "data" }` | | 包围参数 | `/prefix:name(suffix)` | `{ name: "value" }` | | 正则参数 | `/item/:id(\d+)` | `{ id: "456" }` | | 通配符 | `/api/*`, `*/suffix`, `/prefix*suffix` | `{ wildcard: "..." }` | | 正则 | `/^\/api\/(\d+)$/i` | `{ $0, $1, ...命名组 }` | **匹配顺序**: 静态 → 参数 → 通配符 → 正则 ## 示例 ```typescript import { Core } from '@zenweb/core'; import router, { Router } from '@zenweb/router'; const app = new Core(); app.setup(router({ prefix: '/api' })); app.router.get('/users/:id', ctx => { ctx.body = { id: ctx.params.id }; }); // 子路由 const sub = new Router({ prefix: '/admin' }); sub.get('/dashboard', ctx => ctx.body = 'ok'); app.router.add(sub); ``` ## 错误 重复路由注册时抛出 `RouterDuplicated` 错误,可 try-catch 捕获。