Express.js Router
Structured routing for Express.JS
Example
Every route is implemented in a dedicated file
Example:
.
+-- routes
| +-+ todos
| +-- create.js
| +-- update.js
| +-- delete.js
+-- models
| +-- todo.js
+-- server.js
routes/todos/create.js
Example route definition // File: ./routes/todos/create.js 'use strict'; const Todo = ; // The validate function is executed before the responder, allowing// to easily check for the existence of parameters and their format.// If some parameters are not valid, the function must throw an error// // Note: Can be either synchronous or asynchronous. { if !reqbodytext throw 'Missing parameter "text"' } // The respond method is the actual implementation of our route { let text = reqbody; let user = reqpreloadedDatauser; let todo = text user ; await todo; await todo; resstatus201; res;} // The exports describe the route definition.// .path, .method and .respond are required// // Conditions are checked to define wether the route should be// executed or not. You can define as many conditions as you want. path: '/todos' method: 'POST' validate respond conditions : 'isLoggedIn' preload : 'user' ;
server.js
Express app // File: ./app.js 'use strict'; ; ; const app = ; // By enabling debug mode, routes will be logged to stdout; // Conditionals allow us to add handy condition checks all over our approuter; // Preloaders allow us to easily preload resources before the requests are executedrouter; // You can decide if either you want to preload resources sequentially or in parallel//// 0 -> parallel (default)// 1 -> sequential//router; // Finally, create routes by padding the path where they're storedrouter; app;
Remarks:
- Routes prefixed by
_
or namedindex.js
won't be included - You can enable debug mode by calling
router.enableDebug();
- Route creation is recursive.
Changelog:
2.0.0
- Removed
express-validator
- Made validate function support asynchronous execution (using Promises)
- Added
ALL
to match any HTTP method - Allowed
method
to be an array of HTTP methods
License:
MIT