express-autoload-router
v1.0.5
Published
auto create routers from specified folder for Express.js
Downloads
2
Readme
express-autoload-router
Load routers from specific folders for Express.js
Install
npm i express-autoload-router -S
Usage
const path = require('path');
const express = require('express');
const loadRouter = require('express-autoload-router');
const app = express();
// Use `path.join(__dirname, 'path/to/folder')` here
loadRouter(app, '/api', path.join(__dirname, 'controllers'));
Notice
controller filename must end with '_controller.js', like: list_controller.js api function name must endwith 'Action', like: apiAction
Options
loadRouter(app, '/api', path.join(__dirname, 'controllers'));
access url: http://127.0.0.1:4000/api/product/detail
Controller
declaration
There are three kinds of Controller
for this package:
- Plain function
exports.apiAction = (req, res) => {
res.send('API');
};
- Object
Property | Type | Required | Default | Note
---------|--------|----------|---------|-------
method | String Aarry | No | GET
| one of ['GET', 'POST', 'PUT', 'DELETE']
middlewares | Array | No | []
| Array of middlewares, see below
handler | Function | Yes | -- |
e.g.
exports.apiAcion = {
method: ['GET'],
params: [':id'],
handler(req, res) {
res.send('API');
}
};
Middlewares support
This package also support middlewares
in controller
.
e.g.
exports.api = {
method: ['GET'],
middlewares: [
function (req, res, next) {
console.log('Middleware 1');
next();
},
function (req, res, next) {
console.log('Middleware 2');
next();
},
],
handler(req, res) {
return res.send(`product detail ${req.params.id}`);
},
};
Example
See example.
License
The MIT License