forked from marcobarcelos/node-msmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
executable file
·110 lines (88 loc) · 1.86 KB
/
queue.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
import { EventEmitter } from 'events';
import { queueProxy } from './proxy';
export default class Queue extends EventEmitter {
constructor(path) {
super();
this.path = path;
}
static existsQueue(path) {
return queueProxy.exists(path, true);
}
static createQueue(path) {
let result = queueProxy.create(path, true)
if (!result) {
throw new Error('Queue already exists');
}
return new Queue(path);
}
static openOrCreateQueue(path) {
queueProxy.create(path, true);
return new Queue(path);
}
static connectToRemoteQueue(path) {
queueProxy.connectRemote(path, true);
return new Queue(path);
}
startReceiving() {
if (this.receiving) {
throw new Error('Already receiving messages from this queue');
}
this.receiving = true;
return queueProxy.receive({
path: this.path,
receive: (message) => {
this.emit('receive', message);
}
});
}
startPeeking() {
if (this.receiving) {
throw new Error('Already receiving messages from this queue');
}
this.receiving = true;
const start = () => {
this.peek().then(msg => {
this.emit('peek', {
msg,
next: async () => {
await this.remove(msg.id);
start();
}
})
})
};
start();
}
peek() {
return new Promise((resolve, reject) => {
queueProxy.peek(this.path, (error, msg) => {
if (error) reject(error);
else resolve(msg);
});
});
}
remove(id) {
return new Promise((resolve, reject) => {
queueProxy.remove({
path: this.path,
id
}, (error, result) => {
if (error) reject(error);
else resolve(result);
});
})
}
send(message, cb) {
let formattedMessage = JSON.stringify(message);
return queueProxy.send({
path: this.path,
message: formattedMessage
}, cb);
}
getAllMessages() {
return queueProxy.list(this.path, true);
}
purge() {
queueProxy.clear(this.path, true);
}
}