Load routers from specific folders for Express.js
npm i express-load-router -S
const path = require('path');
const express = require('express');
const loadRouter = require('express-load-router');
const app = express();
// Use `path.join(__dirname, 'path/to/folder')` here
loadRouter(app, path.join(__dirname, 'controllers'));
loadRouter(app, path.join(__dirname, 'controllers'), options);
option | type | default |
---|---|---|
excludeRules |
Array | [] |
rewriteRules |
Map | new Map() |
There are three kinds of Controller
for this package:
- Plain function
exports.api = (req, res) => {
res.send('API');
};
- Object
Property | Type | Required | Default | Note |
---|---|---|---|---|
method | String | No | GET |
one of ['GET', 'POST', 'PUT', 'DELETE'] |
params | Array | No | [] |
|
middlewares | Array | No | [] |
Array of middlewares, see below |
handler | Function | Yes | -- |
e.g.
exports.api = {
method: 'GET',
params: [':id'],
handler(req, res) {
res.send('API');
}
};
This package also support middlewares
in controller
.
e.g.
exports.api = {
method: 'GET',
params: [':id'],
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}`);
},
};
See example.
The MIT License