「eggjs装饰器路由库」:egg-blueprint

「eggjs装饰器路由库」:egg-blueprint
最新回答
听海的哭泣ぃ

2023-05-13 19:41:55

egg-blueprint 是一个受 Flask 蓝图启发的 Egg.js 装饰器路由库,通过 TypeScript 装饰器简化了路由管理,支持路由分组、中间件、参数化路径及快速 CRUD 生成等功能。以下是其核心特性和使用方法:

安装与基础配置
  1. 安装库通过 npm 安装依赖:

    npm install --save egg-blueprint
  2. 初始化蓝图在 router.ts 中注册蓝图,可配置全局路由前缀宏搏:

    import { Application } from 'egg';import { Blueprint } from 'egg-blueprint';export default (app: Application) => { Blueprint(app, { prefix: '/api' }); // 全局前缀};
核心特性1. 装饰器路由

使用 @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']; }}
  • 路径参数:通过 :param 捕获动态片段,通过 ctx.params 访问。
2. 全局路由前缀

在初始化时配置 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 上下文)和当前控制器实例。

4. 快速生成 CRUD 接口

通过 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

设计优势
  1. 代码优雅性利用 TypeScript 装饰器抽象路由逻辑,减少样板代码,提升可读性。

  2. 模块化路由通过蓝图分组管理路由,避免集中式路由配置的臃肿问题。

  3. AOP 支持中间件机制实现横切关注点(如认证、日志),符合面向切面编程思想。

  4. TypeScript 集成类型定义完善,提供编译时检查,减少运行时错误。

使用场景
  • API 服务开发:快速构建结构清晰的 RESTful 接口。
  • 多模块项目:按功能划分蓝图,隔离路由逻辑。
  • 中间件复用:统一处理认证、权限等通用逻辑。
注意事项
  • 版本兼容性:确保 Egg.js 和 TypeScript 版本匹配。
  • 中间件顺序:多个中间件按声明顺序执行,需注意依赖关系。
  • 错误处理:中间件中需显式返回 false 或设置 ctx.status 终止流程。

egg-blueprint 通过装饰器和蓝图模式简化了 Egg.js 的路由管理,适合追求代码简洁性和模块化的 TypeScript 项目。更多细节可参考

仓库文档