Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
My usual fixtures loader
// TODO comments (lol)
"use strict";
/**
Usage:
- Put your data in data.json
- Require from your test files `var fixtures = require('./path/to/fixtures')
- Load and clear with `before(fixtures.clear)`, `before(fixtures.load)`, `after(fixtures.clear)`
Data format:
{
"NameOfTheModel": [
{"field": "value", "otherField": 42},
{"field": "anotherItem"}
],
"AnotherModel": [
{"supports": "dbref", "key": {"$ref": "NameOfTheModel", "$idx": 1}}
]
}
**/
var models = require('../../lib/models') // A hash of your Mongoose models
, async = require('async')
, data = require(__dirname + '/data.json'); // The fixtures
module.exports = {
load: function (cb) {
var operations = {};
Object.keys(data).forEach(function (model) {
var Model = models[model];
data[model].forEach(function (object, index) {
var key = model + ':' + index;
var deps = getDependedObjects(object);
operations[key] = deps.concat(function (cb, r) {
(new Model(injectDependedObjects(object, r))).save(function (err, obj) { cb(err, obj); });
});
});
});
async.auto(operations, cb);
},
clear: function (cb) {
var operations = Object.keys(data).map(function (model) {
var Model = models[model];
return Model.remove.bind(Model, {});
});
async.parallel(operations, cb);
}
};
function getDependedObjects (object) {
var deps = [];
Object.keys(object).forEach(function (key) {
if (!object[key]) {
return;
}
if (object[key].$ref && !isNaN(object[key].$idx)) {
addDependedObject(deps, object[key]);
}
if (Array.isArray(object[key])) {
object[key].forEach(function (o) {
deps = deps.concat(getDependedObjects(o));
});
}
});
return deps;
}
function addDependedObject (deps, ref) {
var s = ref.$ref + ':' + ref.$idx;
if (!~deps.indexOf(s)) {
deps.push(s);
}
}
function injectDependedObjects (object, deps) {
var obj = {};
Object.keys(object).forEach(function (key) {
var v = object[key];
if (v && v.$ref && !isNaN(v.$idx)) {
// direct dependency
v = deps[v.$ref + ':' + v.$idx];
} else if (Array.isArray(v)) {
// sub-documents
v = v.map(function (subdoc) {
return injectDependedObjects(subdoc, deps);
});
} /*else { // !v
// v unchanged
}*/
obj[key] = v;
});
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment