Created
February 25, 2015 05:43
-
-
Save rxw1/cf616beb3a6c14aeec4b to your computer and use it in GitHub Desktop.
ref
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
// 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