This pattern takes advantage of lexical scope in javascript, CommonJS modules, and object destructuring. It's a good way to share stateful resources, such as a db connection object, to middleware and detached routers in Express.
/app.js:
const express = require('express')
const app = express()
const errorReporter = require('./modules/errorReporter')
const mainRoute = require('./routes/main')
/* i'm using knex and postgres as an example,
* but of course this will work with anything */
const db = require('knex')({
client: 'pg',
connection: {
host: 'localhost',
database: 'postgres',
}
})
// all the stateful stuff other resources might need
const state = {
db,
errorReporter
}
app.use('/', mainRoute(state))
/routes/main.js:
const express = require('express')
const router = express.Router()
/** first we export a fn to act as a wrapper for our router.
* as you can see, we destructure whatever we need out of the state
* in this case, it's only the db */
module.exports = ({ db }) => {
router.get('/', (req, res) => {
// now my unwraped stateful deps are available in this module
}
return router
}