1.0.2 • Published 5 years ago
decorator-egg v1.0.2
decorator-egg
使用装饰器给 egg 注册路由
Usage
For Install
npm install --save decorator-egg
Setup
In router.ts
or route.js
// router.ts or route.js
import { Application } from 'egg';
import { initRouter } from 'decorator-egg';
export default (app: Application) => {
initRouter(app);
}
Prefix Url Globally
// router.ts or `router.js`
initRouter(app, { prefix: '/api' })
// controller.ts or `controller.js`
import { Get } from 'decorator-egg'
export default class index extends Controller {
@Get('/user') //===>>/api/user
async get() {
this.ctx.body = 'hello, decorator-egg.'
}
}
Prefix Url For Controller
// controller.ts or `controller.js`
import { Router, Get } from 'decorator-egg'
@Router('/home')
export default class home extends Controller {
@Get('/test') //===>>/home/test
async get() {
this.ctx.body = 'hello, decorator-egg.'
}
}
Router Middleware
Router middleware will run before the target function.
Example
import { Controller } from 'egg';
import { Router, Get, Post, Del, Put } from 'decorator-egg';
// @routerDecorator.prefix('/example')
@Router('/example', (ctx, next) => {
console.log(ctx.request.URL);
console.log('ExampleController的prefix中的中间件1');
next();
}, async (ctx, next) => {
await next();
console.log(ctx.request.URL);
console.log('ExampleController的prefix中的中间件2');
})
export default class ExampleController extends Controller {
@Get('/index') // ===>>/example/index get
@Post('/index2') // ===>>/example/index2 post
public async test1 () {
const { ctx } = this;
ctx.body = 'hello, decorator-egg.'
}
@Put('/parms/:id') // ===>>/parms/:id put
public async test2 () {
const { ctx } = this;
ctx.body = 'hello, decorator-egg.'
}
@Del('/parms/:id/:pwd', isLogin, hasDelAuth) // ===>>/parms/:id/:pwd del
public async test3 () {
const { ctx } = this;
ctx.body = 'hello, decorator-egg.'
}
}
// isLogin middleware
const isLogin = async (ctx, next) => {
if (ctx.params['id']) {
await next();
} else {
ctx.status = 401;
}
}
// hasDelAuth middleware
const hasDelAuth = async (ctx, next) => {
if (ctx.params['pwd'] === 'admin') {
await next();
// ctx.body = 'xxx'
} else {
ctx.status = 403;
}
}
The MIT License (MIT)