koa-router 是目前用的比較多的 Koa 的路由中間件之一,前段時間因爲做者沒有精力繼續維護而將其公開售賣。咱們有些項目也用到了這個庫,可是目前不少咱們想要的特性都沒有,好比生成接口文檔。自己這個庫代碼實現還比較簡單,所以綜合考慮打算重寫一個。git
項目地址:https://github.com/d-band/koa...github
index.jsjson
import Koa from 'koa'; import Mapper from 'koa-mapper'; import * as service from './service'; const Mapper = new Mapper(); mapper.get('/users/:id/projects', { params: { id: { type: 'number' }, status: { type: 'array<string>', in: 'query' }, token: { type: 'string', in: 'header' } } }, service.getProjects); mapper.post('/users/:id/projects', { params: { id: { type: 'number' } }, body: 'Project' }, service.addProject); mapper.schema('Project', { id: { type: 'number', required: true }, name: { type: 'string', required: true }, status: { type: 'array<Status>', required: true } }); mapper.schema('Status', { id: { type: 'integer' }, name: { type: 'string' } }, { required: ['id', 'name'] }); app.use(mapper.routes()); app.use(mapper.allowedMethods()); app.listen(3000); // open http://localhost:3000/openapi.json
service.jsapi
export async function getProjects(ctx) { const { id, status, token } = ctx.params; await checkToken(id, token); ctx.body = await Project.findAll({ where: { userId: id, status: { $in: status } } }); } export async function addProject(ctx) { const { body } = ctx.request; ctx.body = await Project.create({ ...body, userId: id }); }
mapper.get(path, [options], ...middlewares); mapper.post(path, [options], ...middlewares); mapper.put(path, [options], ...middlewares); mapper.del(path, [options], ...middlewares); ...
options 爲可選參數,包含:數組
options.params 爲請求參數定義,如:cookie
params = { id: { type: 'number' }, name: { type: 'string', in: 'query' }, user: { type: 'User', in: 'query' } }
number
、string
、integer
、date
、time
、datetime
),數組類型(array<string>
),自定義類型(如 User),自定義數組類型(array<User>
),多個類型(number|string
)mapper.define(schemaName, properties, options); // or mapper.schema(schemaName, properties, options);
支持類型組合,如:app
mapper.schema('Status', { id: { type: 'integer' }, name: { type: 'string' } }, { required: ['id'] }); mapper.schema('Project', { id: { type: 'number', required: true }, name: { type: 'string', required: true }, status: { type: 'array<Status>', required: true } });
支持繼承,如:koa
mapper.schema('Model', { id: { type: 'number' }, createdAt: { type: 'datetime' }, updatedAt: { type: 'datetime' } }); mapper.schema('User: Model', { name: { type: 'string' } });
mapper.post('/users', { body: 'User' }, (ctx) => { const { id, name } = ctx.request.body; });
支持文件上傳,如:async
mapper.post('/uploadImage', { bodyparser: { multipart: true }, body: { user: { type: 'number' }, image: { type: 'file' } } }, (ctx) => { const { user, image } = ctx.request.body; });
目前 koa-mapper 剛發佈,測試覆蓋率達到 100%,有哪些有興趣的小夥伴歡迎一塊兒維護。post