onebeyond / systemic

📦 A minimal dependency injection framework.
https://onebeyond.github.io/systemic
MIT License
56 stars 7 forks source link

Electrician v2 API discussion #1

Closed cressie176 closed 8 years ago

cressie176 commented 8 years ago

@boreplusplus and I have been discussing an electrician rewrite (not sure what we'll call it yet). Here's was we've come up with...

Example Component (electric-mongo)

module.exports = function(options) {

    var MongoClient = options.MongoClient || require('mongodb').MongoClient
    var config, logger, db

    function init(config, components, cb) {
        config = components.config
        logger = components.logger || console.log
        cb()
    }

    function validate(cb) {
       // TODO Add validation here
        cb()
    }

    function start(cb) {
        logger.info('Starting', config.url)
        MongoClient.connect(config.url, config.options, function(err, _db) {      
            cb(err, db = _db)
        })
    }

    function stop(cb) {
        logger.info('Stopping', config.url)
        db.close(cb)
    }

    return {
        start: async.seq(init, validate, start),
        stop: stop
    }
}

system.js

var electrician = require('electrician')
var config = require('./components/confabulous')
var logger = require('./components/prepper')
var mongo = require('./components/mongo')
var rascal = require('./compoments/rascal')
var service = require('./compoments/service')

module.exports = function(options) {    
    return electrician()
          .configure(config())
          .set('logger', logger())
          .set('mongo.primary', mongo()).dependsOn('logger')
          .set('mongo.replica', mongo()).dependsOn('logger')
          .set('express.app', express.app()).dependsOn('logger')
          .set('service', service()).dependsOn('express.app', { logger: 'log' }, 'mongo')
          .set('express.server', express.server()).dependsOn('service')
          .set('broker', rascal)
          .set('rascal.vhosts.jobs.subscribers.job', subscriber).dependsOn('broker')
          .set('rascal.vhosts.jobs.subscribers.employer', subscriber).dependsOn('broker')
}

index.js

var system = require('./system')
system.start((err, components) => {
    if (err) throw error
})

test.js

var system = require('./system')
var testSystem

before((done) => {
    testSystem = system
       .set('broker', { start: stubBroker })
       .start((err, components) => done(err))
})

after((done) => {
    testSystem.stop(done)
})