I've been trying to use JSON configuration file to route node application. I tried to search many ways to do this...but could not success yet.
(The reason that I want to do is, the structure of my project divided as module, and each module folder have its own route code.)
/config/module.json
: Define module structure, and the path that route files are stored in.
[
{
"name" : "my-auth",
"route" : "my-auth/api",
"description" : "Some description about module"
},
{
}
...]
/index.js
const routeEngine = require('./router/engine')
// Use ./router/engine/index.js to route '/api/v1'
app.use('/api/v1', routeEngine)
...
/router/engine/index.js
const fs = require('fs')
const config = require('../../config/module.json')
const express = require('express')
const app = express()
const path = require('path')
module.exports = (app) => {
for (const value of config) {
const poo = fs.readdirSync(path.join(__dirname, '../../module/', value.route))
poo.forEach(file => {
const name = file.substr(0, file.indexOf('.'))
require(path.join(__dirname, '../../module/', value.route, '/', name))(app)
})
}
}
/module/my-auth/api/auth.js
: Many modules include my-auth is in module folder. One module can have several router files.
const express = require('express')
const router = express.Router()
router.get('/product/all', async (req, res) => { some code }
module.exports = router
This is the errors that I got.
(node:18374) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'apply' of undefined
at /home/node_modules/express/lib/router/index.js:635:15
at next (/home/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/home/node_modules/express/lib/router/index.js:174:3)
at router (/home/node_modules/express/lib/router/index.js:47:12)
at poo.forEach (/home/router/engine/index.js:26:83)
at Array.forEach (<anonymous>)
at module.exports (/home/router/engine/index.js:16:13)
at Layer.handle [as handle_request] (/home/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/node_modules/express/lib/router/index.js:317:13)
at /home/node_modules/express/lib/router/index.js:284:7
(node:18374) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)