Skip to content

Instantly share code, notes, and snippets.

@sim51
Last active May 31, 2017 15:05
Show Gist options
  • Save sim51/4ba600a1b2e78d008f96 to your computer and use it in GitHub Desktop.
Save sim51/4ba600a1b2e78d008f96 to your computer and use it in GitHub Desktop.
Tiny Neo4j angular service
'use strict';
// Neo4j configuration
app.constant('NEO4J_USER', 'neo4j');
app.constant('NEO4J_PASSWORD', 'admin');
app.constant('NEO4J_URL', 'http://localhost:7474/db/data/transaction/commit');
'use strict';
/**
* Neo4j service.
*/
app.service('Neo4j', ['$http', '$q', 'NEO4J_URL', 'NEO4J_USER', 'NEO4J_PASSWORD', function ($http, $q, NEO4J_URL, NEO4J_USER, NEO4J_PASSWORD) {
/**
* Execute a cypher query on Neo4j.
*
* @param query Cypher query
* @param params Params of the cypher query
* @returns An array that correspond to the result of the query. Each element must be called by their name.
*/
this.cypher = function (query, params) {
var request = {
method: 'POST',
url: NEO4J_URL,
headers: {
'Authorization': 'Basic ' + btoa(NEO4J_USER + ':' + NEO4J_PASSWORD),
'Accept': 'application/json',
'Content-type': 'application/json; charset=utf-8'
},
data: {
"statements": [
{
"statement": query,
"parameters" : params,
"resultDataContents": ["row"],
"includeStats": false
}
]
}
};
var deferred = $q.defer();
$http(request)
.success(function (body, status, headers, config) {
// If there is some errors we throw an exception
if(body.errors.length > 0) {
var error = '';
body.errors.forEach(function (data, index) {
error += '[' + data.code + ']:' + data.message;
error += '\n';
});
throw new Error(error);
}
// Construct the result
var result = [];
body.results[0].data.forEach(function (line, index) {
var item = {};
body.results[0].columns.forEach(function (col, index) {
item[col] = line.row[index];
});
result.push(item);
deferred.resolve(result);
});
return result;
})
.error(function (data, status, headers, config) {
throw new Error('Bad return value (' + status + ') for REST API. \n\nRequest :' + JSON.stringify(request) + '\n\nResponse :' + JSON.stringify(data));
})
return deferred.promise;
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment