-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsumer.ts
78 lines (71 loc) · 2.07 KB
/
consumer.ts
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
import { IQueue } from "../interfaces/IQueue";
import {
ConsumerHander,
ConsumerProcessOptions,
IConsumer,
} from "../interfaces/IConsumer";
import { ITask } from "../interfaces/ITask";
import { makeDebugger } from "../utils/debugger";
import { delay } from "../utils/delay";
export const DEFAULT_CHECK_INTERVAL = 3000;
/**
* Queue consumer
*/
export class Consumer implements IConsumer {
private static nextId = 1;
private debug: debug.Debugger;
private id: number;
queue: IQueue;
options: ConsumerProcessOptions;
running: boolean = false;
handle: ConsumerHander;
constructor(queue: IQueue, options: ConsumerProcessOptions) {
this.id = Consumer.nextId++;
this.debug = makeDebugger(`consumer#${this.id}:${queue.topic}`);
this.queue = queue;
this.options = options;
this.handle = this.options.handler!;
if (this.options.autorun) {
this.consume();
}
}
get Id(): number {
return this.id;
}
async handleBulk(tasks: ITask[]): Promise<any[]> {
return await Promise.allSettled(
tasks.map(async (task) => {
task.consumerId = this.Id;
return await this.handle(task)
.then(async (result) => {
return await task.complete(result);
})
.catch(async (error) => {
return await task.fail(error);
});
})
);
}
async consume(): Promise<void> {
if (this.running) return;
this.running = true;
this.debug("check waiting");
let tasks = await this.queue.getQueues(this.options.batchSize);
if (tasks.length) {
this.debug(`consume count: ${tasks.length}`);
await this.handleBulk(tasks);
this.running = false;
if (this.options.autorun) {
await delay(async () => await this.consume(), 100);
}
} else {
this.running = false;
if (this.options.autorun) {
await delay(
async () => await this.consume(),
this.options.checkInterval || DEFAULT_CHECK_INTERVAL
);
}
}
}
}