增加README.md文件
This commit is contained in:
2
.npmignore
Normal file
2
.npmignore
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/node_modules
|
||||||
|
package-lock.json
|
70
README.md
Normal file
70
README.md
Normal file
@ -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}
|
||||||
|
});
|
||||||
|
```
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@yizhi/koa-router",
|
"name": "@yizhi/koa-router",
|
||||||
"version": "1.0.0",
|
"version": "1.0.1",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"types": "typing/index.d.ts",
|
"types": "typing/index.d.ts",
|
||||||
"scripts": {},
|
"scripts": {},
|
||||||
|
Reference in New Issue
Block a user