• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

buunguyen/route-decorators: ES7 decorators that simplify Koa and Express route c ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

buunguyen/route-decorators

开源软件地址:

https://github.com/buunguyen/route-decorators

开源编程语言:

JavaScript 100.0%

开源软件介绍:

route-decorators for Koa/Express

NPM

Build Status

ES7 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 $routes array, which you can use to define actual Koa/Express routes.

Assume the above UserCtrl definition, you can define routes in UserCtrl's constructor (although really you can put the code anywhere) as follows:

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

  • @controller(path: optional, ...middleware: optional)
  • @route(method, path: optional, ...middleware: optional)
  • @head, @options, @get, @post, @put, @patch, @del, @delete, @all: wrappers of @route that automatically supply the method argument.

Test

npm install
npm test



鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
KualiCo/koa-pixie-proxy: A proxy module for koa.js发布时间:2022-07-09
下一篇:
Tasktop/java-8-koans: Koans to learn Java 8发布时间:2022-07-09
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap