From 185ff64f100d59c2ac00a899c9a2aa20da3d4ffc Mon Sep 17 00:00:00 2001 From: yizhi <946185759@qq.com> Date: Fri, 11 Oct 2024 17:04:41 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0README.md=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .npmignore | 2 ++ README.md | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 +- 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 .npmignore create mode 100644 README.md diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..5e52727 --- /dev/null +++ b/.npmignore @@ -0,0 +1,2 @@ +/node_modules +package-lock.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..554dde2 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# 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} +}); +``` diff --git a/package.json b/package.json index acce557..cb57d98 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@yizhi/koa-router", - "version": "1.0.0", + "version": "1.0.1", "main": "dist/index.js", "types": "typing/index.d.ts", "scripts": {},