1 Star 0 Fork 17

CharlotteLavoie / egg-decorator-router

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.zh_CN.md 4.24 KB
一键复制 编辑 原始数据 按行查看 历史
fyl080801 提交于 2020-07-02 15:41 . feat: Update version to 1.0.5

egg-decorator-router

NPM version build status Test coverage David deps Known Vulnerabilities npm download

使用装饰器来定义 egg.js 的路由和中间件

依赖说明

依赖的 egg 版本

egg-decorator-router 版本 egg 1.x
1.x 😁
0.x

开启插件

// config/plugin.js
exports.decoratorRouter = {
  enable: true,
  package: 'egg-decorator-router'
}

基于 typescript 的 eggjs 项目可直接使用装饰器
如果是 js 项目,则需要手动安装 babel-plugin-transform-decorators-legacybabel-plugin-transform-object-rest-spread这两个包,并在项目里加入 .babelrc 文件

.babelrc 定义如下:

{
  "plugins": ["transform-decorators-legacy", "transform-object-rest-spread"]
}

使用场景

  • 不用单独定义 router,直接在 controller 里通过装饰器自动生成 router
  • 支持在 controller 里通过装饰器方式加入中间件

规范

Http 请求的完整路径是根路径和子路径合并的结果

在 controller 中先引入依赖

const {
  Route,
  HttpAll,
  HttpGet,
  HttpPost,
  HttpPut,
  HttpPatch,
  HttpDelete,
  Middleware
} = require('egg-decorator-router')

如果使用 typescript

import {
  Route,
  HttpAll,
  HttpGet,
  HttpPost,
  HttpPut,
  HttpPatch,
  HttpDelete,
  Middleware
} from 'egg-decorator-router'

直接在 controller 里定义一个路由

在 controller 里定义一个根路径

// root path is '/'
@Route()

// root path is '/'
@Route('/')

// root path is '/routename'
@Route('/routename')

// root path is '/routename/action'
@Route('/routename/action')

支持定义参数

@Route('/routename/:name')

定义子目录和 HttpMethod

支持 Http 方法 HttpGet HttpPost HttpPut HttpPatch HttpDelete HttpAll

在 controller 方法上定义子目录

// sub-path is '/'
@HttpGet()

// sub-path is '/'
@HttpGet('/')

// sub-path is '/action'
@HttpGet('/action')

// sub-path is '/action/:id'
@HttpGet('/action/:id')

定义中间件

@Middleware(routeM)

示例

'use strict'

const { Controller } = require('egg')
const { Route, HttpGet, Middleware, filters } = require('egg-decorator-router')
const { DefaultFilter } = filters

const routeM = (ctx, next) => {
  console.log('passed route middleware')
  next()
}

const actionM = i => {
  return (ctx, next) => {
    console.log('passed action middleware ' + i)
    next()
  }
}

@Route()
@Middleware(routeM)
class HomeController extends Controller {
  @HttpGet('/') // path: /
  async index() {
    await new Promise(resolve => {
      this.ctx.body = 'ssss'
      resolve()
    })
  }

  @HttpGet() // path: /func1
  @Middleware(actionM(2), 2)
  @Middleware(actionM(1), 1)
  func1(ctx) {
    ctx.body = 'hi, func1'
  }

  @HttpGet('/:id') // path: /:id
  @DefaultFilter('aaa')
  func2(ctx) {
    ctx.body = 'hi, func2 ' + ctx.params.id
  }
}

module.exports = HomeController

License

MIT

JavaScript
1
https://gitee.com/CharlotteLavoie/egg-decorator-router.git
git@gitee.com:CharlotteLavoie/egg-decorator-router.git
CharlotteLavoie
egg-decorator-router
egg-decorator-router
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891