Easy-to-use decorators for writing controllers in egg.js.
Features
- Define routes in together with the controller
- Per-route middleware via decorators
- Common middleware for a controller via decorators
- Zero configuration
Quick glance
import { Controller } from 'egg'
import { Resource, Post, createDecorator } from '../egg-decorators'
const users = [
{ id: 1, username: 'alice', password: '123' },
{ id: 2, username: 'bob', password: '456' }
]
const ReturnBody = createDecorator(async (ctx, next) => {
ctx.body = await next()
})
const Authorized = (self: boolean) => createDecorator((ctx, next) => {
if (ctx.headers.authorization) {
ctx.user = ...
if (!self || ctx.user.id == ctx.params.id) {
return next()
}
}
ctx.status = 401
return 'Unauthorized'
})
@Resource
@ReturnBody
export default class UserController extends Controller {
async index () {
this.ctx.body = users
}
@Authorized(false)
async show () {
this.ctx.body = users.find(user => user.id == this.ctx.params.id)
}
async create () {
users.push(this.ctx.body)
this.ctx.status = 204
}
@Authorized(true)
async update () {
this.ctx.body = 'update resource'
}
@Post('/login')
async login () {
this.ctx.body = 'destroy resource'
}
}
Installation
-
Install egg-decorator
yarn add egg-decorators
npm i egg-decorators --save
-
Enable plugin in config/plugin.js
exports.decorators = {
enable: true,
package: 'egg-decorators',
}