forked from cyx/redic.js
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
131 lines (108 loc) · 2.85 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
'use strict';
const hiredis = require('hiredis');
const slice = Array.prototype.slice;
const reader = new hiredis.Reader();
class Disq {
constructor(config) {
if (config instanceof Function)
this.config = config;
else
this.config = function() { return config || {} };
}
connect() {
if (this.socket)
return Promise.resolve(this.socket);
else {
return Promise.resolve(this.config())
.then(config => {
const addr = config.nodes[0];
const parts = addr.split(':');
this.socket = hiredis.createConnection(parts[1], parts[0]);
this.socket
.on('reply', data => {
if (data instanceof Error)
this._operations.shift()[1](data);
else
this._operations.shift()[0](data);
})
.on('error', error => {
this._operations.shift()[1](error);
});
this._operations = [];
if (config.auth)
return this.call('auth', config.auth);
});
}
}
call() {
return this.connect()
.then(() => {
return new Promise((resolve, reject) => {
this._operations.push([ resolve, reject ]);
this.socket.write.apply(this.socket, arguments);
});
});
}
addjob(queue, job, options) {
if (options) {
const timeout = options.timeout || 0;
const keys = Object.keys(options);
const args = keys
.filter(key => key !== 'timeout')
.map(pairify(options))
.reduce((accum, pair) => accum.concat(pair), []);
return this.call.apply(this, [ 'addjob', queue, job, timeout ].concat(args));
}
else
return this.call('addjob', queue, job, 0);
}
getjob(queue, options) {
const keys = Object.keys(options || {});
const args = keys
.map(pairify(options))
.reduce((accum, pair) => accum.concat(pair), []);
args.push('from', queue);
return this.call.apply(this, [ 'getjob' ].concat(args))
.then(function(jobs) {
return jobs.map(function(job) {
return {
queue: job[0],
id: job[1],
body: job[2]
};
});
});
}
info() {
return this.call('info')
.then(parseInfo);
}
end() {
if (this.socket) {
this.socket.end();
this.socket = null;
}
}
}
function parseInfo(str) {
const result = {};
str
.split("\r\n")
.forEach(function(line) {
if (line.length === 0 || line[0] === '#') return;
const parts = line.split(':');
const key = parts[0];
const value = parts[1];
result[key] = value;
});
return result;
}
function pairify(obj) {
return function(key) {
if (obj[key] === true)
return [ key ];
else
return [ key, obj[key] ];
};
}
module.exports = Disq;