express-autoroutes
v0.9.5
Published
Routes autoloader for Express
Downloads
5
Readme
express-autoroutes
An autoloader for middlewares and routers for express.
Usage:
In our express application, app.js may look like this:
const ExpressAutoroutes = require('express-autoroutes');
const express = require('express');
var app = express();
var autoroutes = new ExpressAutoroutes(__dirname);
autoroutes
.load('middlewares')
.load('routes')
.load('fixes')
.into(app);
Ok, lets suppouse now that we have at the same path level 3 folders more, called middlewares, routes and fixes.
middlewares contains 3 files, auth,js, middleware.js, another_middleware.js
routes contains 1 file (home.js) and 2 directories (users and another_folder).
routes/another_folder contains 1 file(router.js) and 1 folder(nested_folder).
routes/another_folder/nested_folder contains 1 file(nested_module.js)
routes/users contains 1 file(index.js)
fixes contains 2 files(fix_one.js and fix_two);
The example may reproduce this:
const express = require('express');
const authMiddleware = require('./middlewares/auth);
const middleware = require('./middlewares/middleware');
const anotherMiddleware = require('./middlewares/another_middleware);
const fixOne = require('./middlewares/fixes/fix_one');
const fixTwo = require('./middlewares/fixes/fix_two');
const homeRouter = require('routers/home');
const usersRouter = require('routers/users/index');
const anotherFolderRouter = require('routes/another_folder/router');
const nestedRouter = require('routes/another_folder/nested_folder/nested_router');
app.use(anotherMiddleware);
app.use(authMiddleware);
app.use(middleware);
app.use('/home', homeRouter);
app.use('/another_folder/router', anotherRouter);
app.use('/another_doler/nested_folder/nested_router', nestedRouter);
app.use('/users', usersRouter);
app.use(fixOne);
app.use(fixTwo);
Constructor
At construction time, it receives a basePath param, indicating the base path for making loads.
Methods
load(path[, depth])
Loads all the modules found in path and in its subdirectories recursibly. Depth level is allowed by depth param. If the module found is a express router, it use its relative path to the basePath defined at constrution, to build its route. Otherwise, if the module exports a function, it will be interpretated as a middleware. The path for this cases is not important. NOTE: The order of the use will be a-z.
into(app)
Uses into app the loaded middlewares and routes in the order they were loaded.