Skip to content

Instantly share code, notes, and snippets.

@rm-rf-etc
Last active October 24, 2019 03:04
Show Gist options
  • Save rm-rf-etc/3e4b73461333b56e233135fec2d268af to your computer and use it in GitHub Desktop.
Save rm-rf-etc/3e4b73461333b56e233135fec2d268af to your computer and use it in GitHub Desktop.
Cayley Graph Database Example - Get user with friends
function predicatesToList(thingId) {
var thing = g.V(thingId);
var result = [];
thing.outPredicates().map(function(a){
if (!a) return;
thing.out(a.id).map(function(b){
result.push([a.id, b.id]);
});
});
return result;
}
function followLinks(options, data) {
if (options && Object.keys(options).length) {
Object.keys(options).forEach(function(key){
if (!key) return;
var action = key;
var predicate = options[key];
if (action === 'follow') {
data[predicate].forEach(function(nodeId, idx){
data[predicate][idx] = getThing(nodeId, { omit: '<friend>' });
});
}
else if (action === 'omit') {
delete data[predicate];
}
});
}
return data;
}
function collapseArray(arr) {
var result = {};
arr.forEach(function(item) {
var key = item[0];
var val = item[1];
if (key[0] === '<' && key.slice(-1) === '>') {
result[key] = result[key] || [];
result[key].push(val);
}
else {
result[key] = val;
}
});
return result;
}
function getThing(thingId, options) {
var asArray = predicatesToList(thingId);
var asObject = collapseArray(asArray);
var finalResults = followLinks(options, asObject);
finalResults.id = thingId;
return finalResults;
}
g.emit(getThing('uuid12345', { follow: '<friend>' }));
"uuid12345" "email" "[email protected]" .
"uuid12345" "firstName" "Jim" .
"uuid12345" "lastName" "Jones" .
"uuid12345" "worksFor" "Corporation Inc." .
"uuid12345" <friend> "uuid12346" .
"uuid12345" <friend> "uuid12347" .
"uuid12346" "email" "[email protected]" .
"uuid12346" "firstName" "Joe" .
"uuid12346" "lastName" "Smith" .
"uuid12346" "worksFor" "Apple" .
"uuid12346" <friend> "uuid12345" .
"uuid12347" "email" "[email protected]" .
"uuid12347" "firstName" "Alice" .
"uuid12347" "lastName" "Cooper" .
"uuid12347" "worksFor" "LinkedIn" .
"uuid12347" <friend> "uuid12345" .
{
"result": [
{
"<friend>": [
{
"email": "[email protected]",
"firstName": "Joe",
"id": "uuid12346",
"lastName": "Smith",
"worksFor": "Apple"
},
{
"email": "[email protected]",
"firstName": "Alice",
"id": "uuid12347",
"lastName": "Cooper",
"worksFor": "LinkedIn"
}
],
"email": "[email protected]",
"firstName": "Jim",
"id": "uuid12345",
"lastName": "Jones",
"worksFor": "Corporation Inc."
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment