egg-router-rs-decorator
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

egg-router-rs-decorator

装饰者模式写egg-router(Routers for eggjs by decorator pattern)。

Usage

For Install

npm install --save egg-router-rs-decorator

Setup

In router.ts or route.js

// router.ts or route.js
import { Application } from 'egg';
import { initRouter } from 'egg-router-decorator';
 
export default (app: Application) => {
    initRouter(app);
}

Prefix Url Globally

// router.ts or `router.js`
initRouter(app, { prefix: '/api' })
 
// controller.ts or `controller.js`
export default class index extends Controller {
    @routerDecorator.get('/user') //===>>/api/user
    async get() {
        this.ctx.body = 'hello, egg-router-decorator.'
    }
}
 

Prefix Url For Controller

// controller.ts or `controller.js`
import routerDecorator from 'egg-router-decorator';
 
@routerDecorator.prefix('/home')
export default class home extends Controller {
    @routerDecorator.get('/test') //===>>/home/test
    async get() {
        this.ctx.body = 'hello, egg-router-decorator.'
    }
}
 

Router Middleware

Router middleware will run before the target function.

Example

import { Controller } from 'egg';
import router from 'egg-router-decorator';
 
// @router.prefix('/example')
@router.prefix('/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 {
 
    @router.get('/index') // ===>>/example/index get
    @router.post('/index2') // ===>>/example/index2 post
    public async test1 () {
        const { ctx } = this;
        ctx.body = 'hello, egg-router-decorator.'
    }
 
    @router.put('/parms/:id') // ===>>/parms/:id put
    public async test2 () {
        const { ctx } = this;
        ctx.body = 'hello, egg-router-decorator.'
    }
 
    @router.del('/parms/:id/:pwd', isLogin, hasDelAuth) // ===>>/parms/:id/:pwd del
    public async test3 () {
        const { ctx } = this;
        ctx.body = 'hello, egg-router-decorator.'
    }
 
    @router.prefix('/parms/log/', [ 'page' ])
}
 
// 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;
    }
}
 

Readme

Keywords

Package Sidebar

Install

npm i egg-router-rs-decorator

Weekly Downloads

0

Version

1.0.1

License

ISC

Unpacked Size

12.9 kB

Total Files

4

Last publish

Collaborators

  • webrs