在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:buunguyen/route-decorators开源软件地址:https://github.com/buunguyen/route-decorators开源编程语言:JavaScript 100.0%开源软件介绍:route-decorators for Koa/ExpressES7 decorators that simplify Koa and Express route creation. Using these decorators, you can write your controllers like below and have all the routes populated. Koa import {controller, get, post} from 'route-decorators'
@controller('/users', middleware1)
class UserCtrl {
@get('/:id', middleware2, middleware3)
async get(context, next) {}
@post(middleware2)
async post(context, next) {}
} Express import {controller, get, post} from 'route-decorators'
@controller('/users', middleware1)
class UserCtrl {
@get('/:id', middleware2, middleware3)
async get(req, res, next) {}
@post(middleware2)
async post(req, res, next) {}
} Once the decorators are applied, every controller instance will receive a Assume the above Koa import Router from 'koa-66'
// Inside controller constructor
this.router = new Router()
for (const {method, url, middleware, fnName} of this.$routes) {
this.router[method](url, ...middleware, this[fnName].bind(this))
} Express import express from 'express'
// Inside controller constructor
this.router = express.Router()
for (const {method, url, middleware, fnName} of this.$routes) {
this.router[method](url, ...middleware, (req, res, next) => {
this[fnName](req, res, next).catch(next)
})
} You can move the above logic to some base controller in your app and reuse it for every controller. For example: class BaseCtrl {
constructor() {
this.router = new Router()
for (const {method, url, middleware, fnName} of this.$routes) {
this.router[method](url, ...middleware, this[fnName].bind(this))
}
}
}
@controller(...)
class UserCtrl extends BaseCtrl {
// decorated methods as above
} Decorators
Testnpm install
npm test |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论