This plugin provides the ability to read files from a specified directory and create routes based on the contents of the files. It can also easily load and configure different middleware by writing your own RouterFactory class, and simply generate API documents.
$ npm i egg-router-factory --save
- Create the required files
app
+-- http
| +-- get
| | +--index.js
| | +--yourpage.js
| +-- post
| +--api
| +--yourapi.js
+-- factory.js
- Enable plugin
// {app_root}/config/plugin.js
exports.routerFactory = {
enable: true,
package: 'egg-router-factory',
};
- Write your own factory class. In most cases, we only need to inherit RouterFactory and override the setMiddlewares and buildDoc methods.
// {app_root}/app/factory.js
'use strict';
const RouterFactory = require('egg-router-factory');
class MyFactory extends RouterFactory {
// Add middleware one by one according to the configuration
setMiddlewares(obj, args) {
const app = this.app;
if(obj.params) {
args.push(app.middlewares.ajvValidate(obj.params));
}
if(obj.userauth) {
args.push(app.middlewares.userauth(obj.userauth));
}
args.push(app.middlewares.onError);
}
// Generate documents based on route configuration
buildDoc() {
let text = '';
for (let i = 0; i < this.routers.length; i++) {
const obj = this.routers[i];
text += `[${obj.method}]${obj.item.path || obj.path}\n`;
if(obj.item.params){
text += params2doc(obj.item.params);
}
if(obj.item.userauth){
text += userauth2doc(obj.item.userauth);
}
}
return text;
}
}
module.exports = MyFactory;
- Write your router files
// {app_root}/app/http/get/index.js
'use strict';
module.exports = {
path: '/',
controller: 'home.index',
}
// {app_root}/app/http/get/yourpage.js
module.exports = app => {
params: { /* some params configuration */ },
controller: app.controller.home.yourpage,
}
// {app_root}/app/http/post/api/yourapi.js
module.exports = () => {
params: { /* some params configuration */ },
userauth: { /* some auth configuration */ },
async controller() {
/* do something here */
this.body = 'success';
},
}
- Run buildAllRouters in router.js
// {app_root}/app/router.js
'use strict';
module.exports = app => {
app.routerFactory.buildAllRouters(app.router);
};
- Complete! You can also call buildDoc to generate documentation in test cases or elsewhere if needed.
Router configuration file supports two formats
- Export a function containing the unique parameter app, which returns a configuration JSON
- Export a configuration JSON directly
property | required | description |
---|---|---|
controller | true | It can be a string corresponding to the controller, a controller function, or a non-parameter asynchronous function. When it is an asynchronous function with no arguments, the this pointer points to the current ctx. |
name | false | Route name, can be omitted |
path | false | Route path, the default is to use the relative path of the configuration file as the route path. |
see config/config.default.js for more detail.
npm test