Created
August 31, 2018 10:18
-
-
Save adriangrigore/2c951e51120103624cc3b58bdfd87438 to your computer and use it in GitHub Desktop.
fetchTree
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
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