expressjs-routes-loader
v1.1.0
Published
dynamically load routes for your expressjs project
Downloads
5
Readme
express-routes-loader
Routes loader for expressjs. (implementation example here)
Installation
$ npm install expressjs-routes-loader --save
Usage
expressjs-routes-loader
allow you to preload endpoints from specific folders.
For this to be working the way you declare your routes has to follow some conventions. (see example below)
Options
| variable | description | default |
| -------- | ----------- | ------- |
| useNameFolder | folder hierarchie is used as a prefix for your endpoint | false
|
| raiseErrorOnDuplicate | raise an error if there are some duplicated endpoints. | true
|
Example
Your index.js
const path = require('path')
const express = require('express')
const bodyParser = require('body-parser')
const loader = require('expressjs-routes-loader')({ useNameFolder: true }) // can be called without any options if you just want to use to default ones.
let port = process.env.port || 8080
let app = express()
app.use(bodyParser.json())
// register your routes
const dirs = [path.join(__dirname, 'src', 'routes'), 'api']
const routes = loader(dirs)
routes.forEach((route) => {
app[route.method](route.url, route.handler)
})
app.listen(port, function () {
console.log(`App listening on port ${port}`)
})
Route declaration
function post(req, res) {
res.send()
}
function get(req, res) {
res.send()
}
module.exports = [
{
method: 'post',
url: 'users',
handler: post
},
{
method: 'get',
url: 'users/:id',
handler: get
}
]
Advanced
const singleDir = [path.join(__dirname, 'src', 'routes')]
const multipleDirs = [
[path.join(__dirname, 'src', 'routes', 'users')],
[path.join(__dirname, 'src', 'routes', 'events')]
]
You can add prefix to your all of your endpoints
const singleDir = [path.join(__dirname, 'src', 'routes'). 'api'] // /api/...
const multipleDirs = [
[path.join(__dirname, 'src', 'routes', 'users'), 'api', 'users'], // /api/users/...
[path.join(__dirname, 'src', 'routes', 'events'), 'api', 'events'] // /api/events/...
]
Tests
$ npm test