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

xmlking/koa-router-decorators: koa router ES7 decorators

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

开源软件名称:

xmlking/koa-router-decorators

开源软件地址:

https://github.com/xmlking/koa-router-decorators

开源编程语言:

TypeScript 99.1%

开源软件介绍:

Koa Router Decorators

ES7 decorators for koa-router model.

Installation

$ npm i koa-router-decorators --save

Usage

This library supports ES7 decorators proposal which is supported by babel and typescript. To use it with babel you should enable experimental es7.decorators feature in babel as described here. To use it with typescripts you should enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json

 @route(path, HttpMethod, ...middleware)
 optional middlewares are added before the target method. 

See trust-broker for more examples

Example

import {route, HttpMethod} from 'koa-router-decorators';
import User from '../models/User'

@route('/users')
export default class UserController {

  router:Router;

  constructor() {
    return this.router.routes();
  }
  
  @route('/', HttpMethod.GET, isAdmin)
  static *index(next) {
    let query = User.find().skip(0).limit(20);
    let users = yield query.exec();
    let count = yield User.count();
    this.body = {users, count};
  }

  @route('/', HttpMethod.POST)
  static *create(next) {
    let newUser =  new User(this.request.body);
    let result;
    try {
      result = yield newUser.save();
    } catch (err) {
      this.throw( 'DB Error: Unable to save', 500);
    }

    this.status = 201;
    this.body = result
  }
}

function *isAdmin(next) {
  if (!this.state.user.roles.includes('admin')) {
    throw new AuthorizationError(AuthorizationError.code.FORBIDDEN, {message: 'insufficient role (admin only)'});
  }
  yield next;
}

Annotated routes are applied at the end. may overwrite manual added routes if path/method matches.

import koa from 'koa';
import Router from 'koa-router';
import bodyParser from'koa-bodyparser';
import UserController from  './controllers/UserController';

rootRouter = new Router({
  prefix: '/api'
});

app = koa();
app.use(bodyParser());
app.use(new AuthController());
rootRouter.use('/v1', new UserController());
app
  .use(rootRouter.routes())
  .use(rootRouter.allowedMethods());
app.listen(3000);

Development

You need typescript installed globally

npm install -g typescript
npm install -g tslint

build

npm run compile  # or just `tsc`

test

npm test # bug :  if you see error: remove "pretest": "tsc -p ./test" from package.json and try again.

publish to npm registry

npm publish



鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Cacivy/koa-typescript: 发布时间:2022-06-24
下一篇:
LXJS/training-koa发布时间:2022-06-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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