/
publisher-factory.ts
57 lines (52 loc) · 1.74 KB
/
publisher-factory.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
import { RabbitMqPublisherSetupError } from '../errors/rabbitmq-publisher-setup.error';
import { PublisherConfigs } from '../interfaces/publisher-configs';
import { RabbitMqPublisherSetupFunction } from '../interfaces/rabbit-mq-setup-function';
import { Publisher } from '../models/publisher';
import { RabbitMqConnection } from '../models/rabbitmq-connection';
/**
* Factory to build Publisher instances
*/
export class PublisherFactory {
private configs: PublisherConfigs;
private setupFunction: RabbitMqPublisherSetupFunction;
/**
*
* @param connection connection, which every Publisher instance will use
*/
constructor(
private readonly connection: RabbitMqConnection,
) {}
/**
* Sets configs, with which every Publisher instance will be produced
* @param configs
*/
public setConfigs(configs: PublisherConfigs) {
this.configs = configs;
}
/**
* Sets setup function, with which every Publisher instance will be produced
* @param setupFunction
*/
public setCustomSetupFunction(setupFunction: RabbitMqPublisherSetupFunction) {
this.setupFunction = setupFunction;
}
/**
* Returns a Promise, which will resolve with a new Publisher, built with provided configs or custom setup function
* @throws RabbitMqPublisherSetupError
*/
public async newPublisher(): Promise<Publisher> {
try {
const publisher = new Publisher();
if (this.setupFunction) {
publisher.setCustomSetupFunction(this.setupFunction);
await publisher.init(this.connection);
} else {
publisher.setConfigs(this.configs);
await publisher.init(this.connection);
}
return publisher;
} catch (err) {
throw new RabbitMqPublisherSetupError(err.message);
}
}
}