-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlers.ts
86 lines (76 loc) · 2.39 KB
/
handlers.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
79
80
81
82
83
84
85
86
import logging from '../../logging';
import { AbstractMessageTranslator } from '../../message-translators';
import { timeout } from '../../utils';
import { BaseSQS } from './base';
import { SQSProvider } from './providers';
import { SQSClientOptions } from './types';
export class SQSHandler extends BaseSQS {
provider: SQSProvider;
messageTranslator: AbstractMessageTranslator;
started: boolean;
pollingWaitTimeMs: number;
constructor(queueName: string, clientOptions: SQSClientOptions) {
super(clientOptions);
this.provider = new SQSProvider(queueName, clientOptions);
this.messageTranslator = clientOptions.messageTranslator;
this.pollingWaitTimeMs = 30000;
}
start(): void {
if (!this.started) {
logging.info(`Starting AWS Queue ${this.provider.queueName}`);
this.started = true;
this.poll();
}
}
stop(): void {
if (!this.started) {
logging.info(`Stopping AWS Queue ${this.provider.queueName}`);
return void 0;
}
logging.info(`Stopping AWS Queue ${this.provider.queueName}`);
this.started = false;
}
async processMessage(message: any): Promise<void> {
const { content, metadata } =
this.messageTranslator.translateMessage(message);
try {
const handled = await this.handle(content, metadata);
if (handled) {
await this.provider.confirmMessage(message);
}
} catch (err) {
logging.error(`Error handling message ${err}`);
if (err.deleteMessage) {
await this.provider.confirmMessage(message);
} else {
await this.provider.messageNotProcessed(message);
}
}
}
async poll(): Promise<void> {
if (!this.started) {
logging.info(
`Poll was called while consumer was stopped, cancelling poll...`
);
return void 0;
}
logging.info(`Polling AWS Queue ${this.provider.queueName}`);
const messages = await this.provider.fetchMessages();
if (messages) {
logging.info(
`Received ${messages.length} messages from queue ${this.provider.queueName}`
);
messages.forEach((message: any) => {
this.processMessage(message);
});
}
this.callPoll();
}
async callPoll(): Promise<void> {
await timeout(this.pollingWaitTimeMs);
await this.poll();
}
async handle(_content: object, _metada: object): Promise<boolean> {
throw new Error('Method not implemented.');
}
}