-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
92 lines (75 loc) · 2.01 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
var r = require('rethinkdb')
, debug = require('debug')('reql-then')
, Pool = require('generic-pool').Pool
, Promise = require('bluebird');
var pools = {};
function connectionKey (conn) {
return conn.host + ':' + conn.port;
}
function validateConfig (config) {
if (typeof config === 'undefined') {
config = {};
} else if (typeof config === 'string') {
config = {host: config};
}
config.host = config.host || 'localhost';
config.port = config.port || 28015;
return config;
}
function createPool (key, config) {
debug('createPool: %s', key);
return Pool({
name: 'rethinkdb://' + key,
create: function (callback) {
debug('new: %s', key);
return r.connect(config, callback);
},
validate: function (conn) {
debug('validate: %s', connectionKey(conn));
return conn.open;
},
destroy: function (conn) {
debug('destroy: %s', connectionKey(conn));
conn.close();
},
min: 1,
max: config.maxPoolSize || 10,
log: debug
});
}
function connect (config) {
config = validateConfig(config);
var key = connectionKey(config)
, pool = pools[key] || (pools[key] = createPool(key, config))
, reql;
reql = function (query) {
var acquire = Promise.promisify(pool.acquire, pool)
, run = Promise.promisify(query.run, query);
debug('acquiring: %s', key);
return acquire().then(function (conn) {
debug('acquired: %s', connectionKey(conn));
return run(conn).finally(function () {
debug('releasing: %s', connectionKey(conn));
pool.release(conn);
});
});
};
reql.lazy = function (query) {
return function () {
return reql(query);
};
};
reql.close = function () {
var drain = Promise.promisify(pool.drain, pool);
debug('closing: %s', key);
return drain().then(function () {
debug('destroyAllNow: %s', key);
pool.destroyAllNow();
});
};
reql.getConnectionPool = function () {
return pool;
};
return reql;
}
module.exports = connect;