Skip to content

Instantly share code, notes, and snippets.

@adriangrigore
Created August 31, 2018 10:18
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 adriangrigore/2c951e51120103624cc3b58bdfd87438 to your computer and use it in GitHub Desktop.
Save adriangrigore/2c951e51120103624cc3b58bdfd87438 to your computer and use it in GitHub Desktop.
fetchTree
function fetchTree(url, key, entityId, cb, parent) {
var tree;
var done = function(dst, src) {
for (var i = 0; i < src.length; i++)
if (dst[i].entities.length !== src[i].entities.length)
return false;
return true;
};
fetchEntity(url, key, entityId, function(err, entity) {
if (err) throw err;
tree = {
entity: entity
}
var stream = fetchRelationships(url, key, {entityId: entityId});
collect(function(err, rs) {
if (err) throw err;
tree.relationships = [];
// for (var i = 0; i < rs.length; i++) {
rs.forEach(function(r, i) {
var r = rs[i];
var rb = {
type: r.type,
entities: []
};
tree.relationships[i] = rb;
for (var j = 0; j < r.entities.length; j++) {
var id = r.entities[j];
if (id === tree.entity.id) {
rb.entities[j] = tree;
}
else if (parent !== undefined && id === parent.entity.id) {
rb.entities[j] = parent;
}
else
fetchTree(url, key, id, function(err, branch) {
if (err) throw err;
rb.entities.push(branch);
if(done(tree.relationships, rs))
cb(null, tree);
}, tree);
if(done(tree.relationships, rs)) {
cb(null, tree);
}
}
});
// }
})(stream);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment