Created
May 4, 2014 11:37
-
-
Save Vadorequest/11515067 to your computer and use it in GitHub Desktop.
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
///<reference path='./def/defLoader.d.ts'/> | |
import populate = require('./../../shared/lib/core/lib/CorePopulate'); | |
/** | |
* Used to populate the database to fill it with the default values. | |
*/ | |
export class Populate extends populate.CorePopulate { | |
/** | |
* Run the population for all populate files, execute the population for all documents in all files in parallel. | |
* Use synchronize library to count the created documents. | |
*/ | |
public static populate(){ | |
// Read all files inside the populate folder. | |
fs.readdir(__config.path.populate, function(err, files){ | |
if(err){ | |
consoleDev(err); | |
}else{ | |
sync.fiber(function() { | |
sync.parallel(function () { | |
Populate._populate(files); | |
}); | |
// Wait for all parallel process to be done. | |
var messages: Message[] = sync.await(); | |
var created = 0; | |
_.each(messages, function(message: Message){ | |
if(message.hasMessage()){ | |
console.log(message.getMessage()); | |
} | |
created += message.getDataByKey('created', 0); | |
}); | |
console.log(created + ' documents were created, there are now ' + messages.length + ' populated documents.') | |
}); | |
} | |
}); | |
} | |
/** | |
* Retrieve the documents in each file to populate. | |
* Automatically create the document if it's not found in the database. | |
* Use Synchronize library to defer the callback. | |
* | |
* @param files Files where to look for documents to populate. | |
* @private | |
*/ | |
private static _populate(files){ | |
// For each file, get the data to populate stored in the file. | |
_.each(files, function(file){ | |
_.each(require(__config.path.base + __config.path.populate + file), function(documents){ | |
var callback = sync.defer(); | |
// The file name must be the same as the targeted model. | |
var Model = __Dao.getModel(file.split('.')[0]);// Filter the extension. | |
if(Model){ | |
// For each data, try to add it if it does not exist in the DB. | |
Model.findOrCreate(documents, function(err, doc, created){ | |
if(err){ | |
callback(err); | |
}else if(created){ | |
callback(null, new __message('The following document was created in the [' + Model.modelName + '] collection: ' + JSON.stringify(doc), {created: 1}, true)); | |
}else{ | |
callback(null, new __message(null, null, true)); | |
} | |
}); | |
}else{ | |
callback(new __message('Unable to populate the file: ' + file + '. The model was not found.')); | |
} | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment