Hey there! I'm currently working on injecting some dependencies into an expressjs route middleware.
Usually, in your main application, you would typically do something like this:
const express = require('express');
const userRouter = require('./routes/users.js');
const app = express();
app.use('/users', userRouter);
Then, in your users.js
file, you might have something similar to this:
const express = require('express');
const router = express.Router()
router.post('/user', function (req, res, next) {...}
router.get('/user/:id', function (req, res, next) {...}
router.put('/user/:id', function (req, res, next) {...}
router.delete('/user/:id', function (req, res, next) {...}
However, I'm interested in passing some dependencies, like a service URL, and I'm not finding clear instructions on how to accomplish this based on the documentation. I was thinking of something like this:
const express = require('express');
function userRoutes(options) {
const router = express.Router();
router.post('/user', function (req, res, next) {...}
router.get('/user/:id', function (req, res, next) {...}
router.put('/user/:id', function (req, res, next) {...}
router.delete('/user/:id', function (req, res, next) {...}
return router
}
module.exports.userRoutes = userRoutes;
Then, in my main application, I would use it like this:
const userRouter = require('./routes/users.js');
const app = express();
app.use('/users', userRouter.userRoutes(options));
However, when I try to do this, I encounter the following error:
Users/jm/Private/Projects/api-gateway/node_modules/express/lib/router/index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (/Users/jm/Private/Projects/api-gateway/node_modules/express/lib/router/index.js:458:13)
at EventEmitter.<anonymous> (/Users/jm/Private/Projects/api-gateway/node_modules/express/lib/application.js:220:21)
at Array.forEach (native)
at EventEmitter.use (/Users/jm/Private/Projects/api-gateway/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/Users/jm/Private/Projects/api-gateway/app.js:28:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
If you have any suggestions or solutions, they would be greatly appreciated.