Skip to content

Instantly share code, notes, and snippets.

@foxbunny
Created July 26, 2011 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxbunny/1107335 to your computer and use it in GitHub Desktop.
Save foxbunny/1107335 to your computer and use it in GitHub Desktop.
Fixture module
// Loads fixtures using given data, and executes callback
//
// The fixutres are loaded in recursive callbacks from the documents' save
// methods, therefore the loadFixtures call is asynchronous itself, even though
// it will load documents serially.
//
// When using loadFixtues in testing, you need to keep above in mind. Running
// multiple tests that use loadFixtures one after another _will_ cause trouble.
//
// The callback function is passed data that has been entered into the
// database, and a callback function that will wipe the database if it is
// called. You do not need to call this function if you do not wish the tear
// down the fixtures after the test. This callback will also accept a single
// argument, which is a post-tear-down callback.
//
// The ``done`` parameter is used internally to keep track of state between
// recursions. You should not pass anything as ``done`` unless you know what
// you are doing.
//
// @param Model, mongoose model object (or object that implements same API)
// @param data, array of objects to pass to Model's constructor
// @param callback(data, next), callback function, expects data and next
// @param done, list of document instances that were processed
// @api public
function loadFixtures(Model, data, callback, done) {
var currentItem, itemsLeft, document;
function worker() {
// Done is passed by ref always, it maintains state between recursions.
// We only initialize it if it's not passed.
done = done || [];
if (!(data && data.length)) {
// No more left
return callback(done, function(next) {
Model.remove({}, function(err) {
if (typeof next === 'function') {
next(err);
}
});
});
} else {
// There's still to go
currentItem = data[0];
itemsLeft = data.slice(1);
// Create a document from the current item
document = new Model(currentItem);
document.save(function(err, doc) {
// This is called later, when document is saved
// Let's assume there were no errors
// Let's add the freshly baked doc to done array
done.push(doc);
// Let's recurse
loadFixtures(Model, itemsLeft, callback, done);
});
}
}
if (done && done.length) {
// If this is not the first iteration, don't wipe the database
worker();
} else {
// Clean up the database if this is the first iteration
Model.remove(function() {
worker();
});
}
}
exports.load = exports.withFixtures = loadFixtures;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment