Answer the question
In order to leave comments, you need to log in
How to use a function returned by another function as a handler?
I'm learning nodejs, now I'm trying to organize routes on express in a way similar to laravel. Code example:
// Router
const controller = require('../controllers/index')
module.exports = (app) => {
app.get('/users', controller('[email protected]'))
}
// Controller index aka controller()
const fs = require('mz/fs')
module.exports = (handler) => {
const [controller, method] = handler.split('@')
const controllers = fs
.readdirSync(__dirname)
.filter((v) => v !== __filename.slice(__dirname.length + 1))
.map(v=> v.slice(0,-3))
if (controllers.includes(controller)) {
return require(`./${controller}`)[method]
} else {
console.error(`Controller with name ${controller} doesnt exist!`)
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question