2023-05-13 19:41:55
egg-blueprint 是一个受 Flask 蓝图启发的 Egg.js 装饰器路由库,通过 TypeScript 装饰器简化了路由管理,支持路由分组、中间件、参数化路径及快速 CRUD 生成等功能。以下是其核心特性和使用方法:
安装与基础配置安装库通过 npm 安装依赖:
npm install --save egg-blueprint初始化蓝图在 router.ts 中注册蓝图,可配置全局路由前缀宏搏:
import { Application } from 'egg';import { Blueprint } from 'egg-blueprint';export default (app: Application) => { Blueprint(app, { prefix: '/api' }); // 全局前缀};使用 @bp.route 或简写装饰器(如 @bp.get)定义路槐祥由,支持动态参数:
import { bp } from 'egg-blueprint';export default class IndexController extends Controller { @bp.route.get('/') // 基础路由 async get() { this.ctx.body = 'hello, egg-blueprint'; } @bp.get('/foo/:bar') // 动态参数 async getWithID() { this.ctx.body = this.ctx.params['bar']; }}在初始化时配置 prefix,所有路由自动添加前缀:
// router.tsBlueprint(app, { prefix: '/api' });// 控制器路由@bp.get('/user') // 实际路径: /api/userasync getUser() { ... }3. 路由中间件在路由定义中插入中间件函数,控制执行流程:
const Auth = (ctx: Context, ctl: Controller) => { if (ctx.params['password'] === '1234') return true; ctx.body = 'can not see'; return false;};export default class TestController extends Controller { @bp.get('/need/auth/:password', Auth) // 中间件校验 async needAuth() { this.ctx.body = 'authed'; }}返回 false:终止后续执行。
返回 true 或 undefined:铅绝搏继续执行路由方法。
参数:接收 ctx(Koa 上下文)和当前控制器实例。
通过 bp.restfulClass 快速创建 RESTful 资源,重写方法自定义逻辑:
import { bp } from 'egg-blueprint';bp.restfulClass('blueprint', Auth); // 注册资源并应用中间件export default class IndexController extends Controller { async Get() { // GET /blueprint this.ctx.body = 'Fetch data'; } async Post() { // POST /blueprint this.ctx.body = 'Create data'; } async Put() { // PUT /blueprint/:id this.ctx.body = 'Update data'; } async Del() { // DELETE /blueprint/:id this.ctx.body = 'Delete data'; }}Get → GET /resource
Post → POST /resource
Put → PUT /resource/:id
Del → DELETE /resource/:id
代码优雅性利用 TypeScript 装饰器抽象路由逻辑,减少样板代码,提升可读性。
模块化路由通过蓝图分组管理路由,避免集中式路由配置的臃肿问题。
AOP 支持中间件机制实现横切关注点(如认证、日志),符合面向切面编程思想。
TypeScript 集成类型定义完善,提供编译时检查,减少运行时错误。
egg-blueprint 通过装饰器和蓝图模式简化了 Egg.js 的路由管理,适合追求代码简洁性和模块化的 TypeScript 项目。更多细节可参考