Skip to content

Instantly share code, notes, and snippets.

@juliangoacher
Created June 12, 2017 17:40
Show Gist options
  • Save juliangoacher/b03ca3549c0e009788358a5d439f2531 to your computer and use it in GitHub Desktop.
Save juliangoacher/b03ca3549c0e009788358a5d439f2531 to your computer and use it in GitHub Desktop.
Async service startup for node.js
// General app backbone. Start a sequence of services, arranged in dependency order,
// and attach to the app backbone.
const Q = require('q');
// Start the app by completing a sequence of startup steps.
function start( steps ) {
// Convert steps to list of deferreds.
steps = steps.map( ( step ) => {
return ( app ) => {
// Convert step to list of deferred service steps.
var services = Object.keys( step )
.map( ( sname ) => {
console.log('Binding %s...', sname);
// Lookup the service binding.
var service = step[sname];
// If service is a function then invoke, passing in the app backbone.
if( typeof service === 'function' ) {
service = service( app );
}
// Wait for service to complete starting...
return Q( service )
.then( ( service ) => {
// ...then bind to the backbone under its name.
app[sname] = service;
return app;
});
});
// Resolve all services for the current step.
return Q.all( services );
};
});
// Resolve all steps in sequence (to ensure dependency order).
return steps.reduce( Q.when, Q( {} ) )
}
// Start app services in dependency order
var app = start([
{ settings: loadSettings },
{ db: startDB },
{ http: startHTTP }
]);
// Function to load settings - returns a promise resolving to app config.
function loadSettings() {
return Q.nfcall( require('fs').loadFile, 'settings.js' )
.then( ( data ) => {
return JSON.parse( data.toString() );
});
}
// Start the DB - return a promise which resolves once the DB is started.
function startDB( app ) {
// Load DB module and pass it the DB settings.
return require('dbmodule').start( app.settings.db );
}
function startHTTP( app ) {
return require('httpmodule').start( app.settings.http );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment