M
M
Mazino2019-09-26 19:06:30
JavaScript
Mazino, 2019-09-26 19:06:30

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!`)
  }
}

The question is how to rewrite it correctly so that the handler was correctly passed to the route?
upd: The idea is to make the get() method pass the arguments to whatever function the controller() will return

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question