As a toy project, I started evaluating the Neo4J graph database and its Rest interface. I'm trying to write a simple graph visualization in JavaScript. In daily business I'm a Java developer and maybe that's the reason why I'm not that happy with my current approach. In Java I would have written a Neo4J
class, with inner (data) classes for Node
and Relation
as their id
is tightly couple to the server (http://localhost:7474/db/data/node/0
). Maybe they even would get a common parent class.
In JavaScript I don't get away from my object oriented mind. I need some ideas in relation to JavaScript best practice.
function Neo4J(server) {
this.server = server;
}
function Node(connection, response) {
this.id = connection.sanitizeId(response['self']);
this.data = response['data'];
}
function Relation(connection, response) {
this.id = connection.sanitizeId(response['self']);
this.start = connection.sanitizeId(response['start']);
this.end = connection.sanitizeId(response['end']);
this.type = response['type'];
}
Neo4J.prototype = {
sanitizeId: function (id) {
return id.replace(this.server, "");
},
query: function (query, success) {
return post(this.server + "/cypher", {"query": query, "params": {} }, success);
},
getAllNodes: function (callback) {
var connection = this;
this.query("MATCH n RETURN n", function (nodes) {
$.each(nodes['data'], function (i, val) {
callback(new Node(connection, val[0]));
});
});
},
getAllRelations: function (callback) {
var connection = this;
this.query("START r=rel(*) RETURN r", function (nodes) {
$.each(nodes['data'], function (i, val) {
callback(new Relation(connection, val[0]));
});
});
},
getNode: function (id, callback) {
var connection = this;
get(this.server + id + "/properties", function (data) {
if (data == null) data = {data: {}};
else data = {data: data};
data['self'] = id;
callback(new Node(connection, data));
});
},
createNode: function (callback) {
var connection = this;
post(this.server + '/node', null, function (data) {
callback(new Node(connection, data));
});
},
setNodeProperty: function (node, key, value, callback) {
put(this.server + node.id + '/properties/' + key, '"'+value+'"', function (data) {
node.data[key] = value;
callback(node);
});
},
createRelation: function (start, target, type, callback) {
var connection = this;
post(this.server + start + '/relationships', {to: this.server + target, type: type}, function (data) {
callback(new Relation(connection, data));
});
}
}
The post()
and put()
are just ajax calls to the Neo4J server.