Wednesday, 31 May 2017

Proper es6 way of sharing global with sub-modules

I have a complex server-side node module in folder form:

store
  |-index.js
  |-accounts
      |-index
      |-consumer.js
      |-provider.js
  |-site
      |-index.js
      |-portal.js
  |-etc.

Where, in site/index.js I am initialising a database context that should be accessible to all sub-modules (accounts, site, etc.) and exporting all of the sub-module interfaces, like:

import dbdriver from 'mydbdriver'
import settings from './settings'

const db = dbdriver.connect(settings)

export * from '../accounts' // depends on db
export * from '../site'     // depends on db

I have considered polluting the sub-module APIs via arguments (i.e. requiring the context to be passed into all relevant calls), but this is ugly, IMO.

Another idea is to have an initialiser for each module that would accept the context and cash in a module-scoped global, which would be required for every single file (again, yuck.)

Is there a cleaner, elegant es6 way of approaching this?



via Dallas

No comments:

Post a Comment