-
Notifications
You must be signed in to change notification settings - Fork 664
Expand file tree
/
Copy pathqueue-events-producer.ts
More file actions
66 lines (60 loc) · 1.71 KB
/
Copy pathqueue-events-producer.ts
File metadata and controls
66 lines (60 loc) · 1.71 KB
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
import { QueueEventsProducerOptions } from '../interfaces';
import { QueueBase } from './queue-base';
import { RedisConnection } from './redis-connection';
/**
* The QueueEventsProducer class is used for publishing custom events.
*/
export class QueueEventsProducer extends QueueBase {
constructor(
name: string,
opts: QueueEventsProducerOptions = {
connection: {},
},
Connection?: typeof RedisConnection,
) {
super(
name,
{
blockingConnection: false,
...opts,
},
Connection,
);
this.opts = opts;
}
/**
* Publish custom event to be processed in QueueEvents.
* @param argsObj - Event payload
* @param maxEvents - Max quantity of events to be saved
*/
async publishEvent<T extends { eventName: string }>(
argsObj: T,
maxEvents = 1000,
): Promise<void> {
const client = await this.client;
const key = this.keys.events;
const { eventName, ...restArgs } = argsObj;
const args: any[] = ['MAXLEN', '~', maxEvents, '*', 'event', eventName];
for (const [key, value] of Object.entries(restArgs)) {
// Object values would otherwise be stringified by Redis as
// "[object Object]". Serialize them as JSON so consumers can
// parse them back into the original structure.
args.push(
key,
typeof value === 'object' && value !== null
? JSON.stringify(value)
: value,
);
}
await client.xadd(key, ...args);
}
/**
* Closes the connection and returns a promise that resolves when the connection is closed.
*/
async close(): Promise<void> {
if (!this.closing) {
this.closing = this.connection.close();
}
await this.closing;
}
}