在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:xpepermint/koa-controller开源软件地址:https://github.com/xpepermint/koa-controller开源编程语言:JavaScript 100.0%开源软件介绍:koa-controller
InstallationInstall the npm package.
Attach the middleware. var koa = require('koa');
var app = koa();
var kc = require('koa-controller');
app.use(kc.tools()); // optional
app.use(kc.router());
app.listen(3000); By default the middleware expects that controllers exist at app.use(controller({
routesPath: 'my/path/routes.js',
controllerPath: 'my/controllers/{controller}.js', // note that {controller} is a variable
constraintPath: 'my/constraints/{constraint}.js', // note that {constraint} is a variable
logger: console.log // custom logger function
})); Note that RoutesRoutes file is a simple key-value object where the // config/routes.js
module.exports = {
// controller#action
'/users/:id?': { to: 'users#find' },
'post /users': { to: 'users#create' },
'put|post /users/:id': { to: 'users#update' },
'get /users/:id/words/:slug*': { to: 'events#words' },
'get /event/:slug+': { to: 'events#index', constraint: 'api#ip' },
// redirections
'get /to/google': { to: 'http://www.google.com' },
'get /to/home': { to: '/' },
// using a function
'get /events/:id': { to: function *(id) { this.body = ... } },
...
}; You check koa-route and path-to-regexp for more information. ControllerController is a simple key-value object where the // app/controllers/users.js
module.exports = {
find: function*() {
this.body = ...;
},
update: function*(id) {
},
words: function*(id, slug) {
},
...
}; Notice the ConstraintConstraint is a simple key-value object where the // app/constraints/api.js
module.exports = {
ip: function*(next) {
if (this.request.ip == '192.168.1.100') { // allow access only from this IP address
yield next;
} else {
this.body = 'Unauthorized IP address';
this.status = 401;
}
},
...
}; Note that constraints are very much like controllers thus every constraint action has access to Koa context. Check koa-route for details. ToolsBy attaching ctx.form([names])Type: Parsed request body data. You can retrive only selected attributes by specifying a list of console.log( _.form() );
// -> { 'name': 'John', 'email': '[email protected]', 'age': 33 }
console.log( _.form('name', 'age') );
// -> { 'name': 'John', 'age': 33 } |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论