Skip to content

Instantly share code, notes, and snippets.

@rxw1
Created February 25, 2015 05:43
Show Gist options
  • Save rxw1/cf616beb3a6c14aeec4b to your computer and use it in GitHub Desktop.
Save rxw1/cf616beb3a6c14aeec4b to your computer and use it in GitHub Desktop.
ref
// jshint esnext:true
function linkResources(data) {
_.each(data, function(resources, _key) {
let key = _key;
_.each(resources, function(resource, resourceIdx, resources) {
var refs = _.pick(resource, function(refId, refKey) {
return /_id/.test(refKey) && refId;
});
if (_.size(refs)) {
_.each(refs, function(refId, _refKey) {
let refKey = pluralize(_refKey.slice(0, -3));
let ref = _.filter(data[refKey], {
id: refId
})[0];
// ref
if (!resource.hasOwnProperty(resource.type)) {
Object.defineProperty(resource, ref.type, {
get: function() {
return ref;
}
});
}
// reverse ref
if (!ref.hasOwnProperty(key)) {
Object.defineProperty(ref, key, {
get: function() {
let children = _.filter(resources, {
[ref.type + '_id']: ref.id
});
return children;
}
});
}
});
}
});
});
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment