comparison neo4j_driver.js @ 0:aa7a5cc0f59b default tip

commit
author ryo_tas <yamanaka@genome.rcast.u-tokyo.ac.jp>
date Tue, 30 Dec 2014 18:27:26 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:aa7a5cc0f59b
1 /***
2 * Excerpted from "Seven Databases in Seven Weeks",
3 * published by The Pragmatic Bookshelf.
4 * Copyrights apply to this code. It may not be used to create training material,
5 * courses, books, articles, and the like. Contact us if you are in doubt.
6 * We make no guarantees that this code is fit for any purpose.
7 * Visit http://www.pragmaticprogrammer.com/titles/rwdata for more book information.
8 ***/
9 var http = require('http');
10
11 exports.createClient = function(options) {
12
13 options = options || {};
14
15 var
16 running = 0,
17 backlog = [],
18 host = options.host || 'localhost',
19 port = options.port || 7474,
20 limit = options.limit || 10;
21
22 function dequeue() {
23 if (backlog.length && running < limit) {
24 req.apply(null, backlog.shift());
25 }
26 }
27
28 function req(method, path, data, callback) {
29 running += 1;
30 return http
31 .request({
32 host: host,
33 port: port,
34 path: '/db/data/' + (path.join ? path.join('/') : path),
35 headers: {'Content-Type':'application/json'},
36 method: method
37 }, function(res){
38 var buffer = '';
39 res.on('data', function(chunk){
40 buffer += chunk;
41 });
42 res.on('end', function(){
43 var output;
44 if (callback && buffer != '') {
45 try {
46 output = JSON.parse(buffer);
47 } catch (err) {
48 console.error(err);
49 }
50 callback(output, res);
51 }
52 running -= 1;
53 dequeue();
54 });
55 })
56 .on('error', function(){
57 running -= 1;
58 backlog.push([method, path, data, callback]);
59 dequeue();
60 })
61 .end(data ? JSON.stringify(data) : undefined);
62 };
63
64 return {
65 get: function(path, callback) {
66 backlog.push(['GET', path, null, callback]);
67 dequeue();
68 },
69 post: function(path, data, callback) {
70 backlog.push(['POST', path, data, callback]);
71 dequeue();
72 }
73 };
74
75 }
76