在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:xmlking/koa-router-decorators开源软件地址:https://github.com/xmlking/koa-router-decorators开源编程语言:TypeScript 99.1%开源软件介绍:Koa Router DecoratorsES7 decorators for koa-router model. Installation$ npm i koa-router-decorators --save UsageThis library supports ES7 decorators proposal which is supported by babel and typescript.
To use it with babel you should enable experimental
See trust-broker for more examples Exampleimport {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); DevelopmentYou 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 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论