Last active
August 29, 2015 14:05
-
-
Save rektide/c5ca7c74d34e29d72131 to your computer and use it in GitHub Desktop.
async loading module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path'); | |
var mongoose = require('mongoose'); | |
var when = require('when'); | |
var whenNode = require('when/node'); | |
var glob = whenNode.lift(require('glob')); | |
var config = require('./config'); | |
// exports a 'done' promise | |
var done = when.defer(); | |
module.exports = done.promise; | |
// open db | |
var url = config.get('mongoUrl'); | |
mongoose.connect(url); | |
// find db-ready | |
var dbReady = when.defer(); | |
mongoose.connection.once('open', dbReady.resolve.bind(dbReady)); | |
// read all files in the /schema subdir | |
var schemaPath = path.join(__dirname + '/schema/*.js'); | |
var dirRead = glob(schemaPath); | |
// when everything ready, | |
// load all the schema files into mongoose | |
var schemas = when.all([dirRead, dbReady]).then(function(val){ | |
var rv = {} | |
var schemaFiles = val[0]; | |
// load each schema, install into mongoose, and export it here. | |
schemaFiles.forEach(function(schemaFile){ | |
// get the schema | |
var modelModule = require(schemaFile); | |
// load the schema in mongoose | |
var modelName = schemaFile.charAt(0).toUpperCase() + schemaFile.substring(1); | |
var model = mongoose.model(modelName, modelModule); | |
// export the schema | |
rv[modelName] = module.exports[modelName] = model; | |
}); | |
// return a second, non-promise copy of the schemas | |
return rv | |
}) | |
// resolve done when schemas have all loaded | |
schemas.then(function(schemas){ | |
done.resolve(schemas); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment