Skip to content

Instantly share code, notes, and snippets.

@jkantr
Last active September 18, 2018 21:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkantr/b3706357a831108579bb0f152b7768cb to your computer and use it in GitHub Desktop.
Save jkantr/b3706357a831108579bb0f152b7768cb to your computer and use it in GitHub Desktop.
Fun with Express patterns

Express patterns

Parametric modules

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.

Basic setup

/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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment