-
Notifications
You must be signed in to change notification settings - Fork 0
/
publisher-factory.ts
101 lines (84 loc) · 2.6 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
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
import { PublishStrategy } from "./publish-strategy.ts";
import { Notification } from "./notification.ts";
import { NotificationHandler } from "./types.ts";
export interface IPublisher {
publish<TNotification extends Notification>(
notification: TNotification,
handlers: Array<NotificationHandler<TNotification>>,
): Promise<void>;
}
const buildPublisher = (publish: IPublisher["publish"]): IPublisher => ({
publish,
});
const parallelNoWaitPublisher = buildPublisher((notification, handlers) => {
Promise.all(
handlers.map((handler) => handler(notification)?.catch(() => {})),
);
return Promise.resolve();
});
const parallelWhenAnyPublisher = buildPublisher(async (
notification,
handlers,
) => {
const result = await Promise.any(
handlers.map((handler) =>
handler(notification)?.catch((error): Error => error)
),
);
if (result != null) {
throw result;
}
});
const parallelWhenAllPublisher = buildPublisher(
async (notification, handlers) => {
const results = await Promise.all(
handlers.map((handler) =>
handler(notification)?.catch((error): Error => error)
),
);
const aggregateErrors: Error[] = results
.filter((error): error is Error => error != null);
if (aggregateErrors.length > 0) {
throw new AggregateError(aggregateErrors);
}
},
);
const syncContinueOnExceptionPublisher = buildPublisher(
async (notification, handlers) => {
const aggregateErrors: Error[] = [];
for (const handler of handlers) {
try {
await handler(notification);
} catch (error) {
aggregateErrors.push(error);
}
}
if (aggregateErrors.length > 0) {
throw new AggregateError(aggregateErrors);
}
},
);
const syncStopOnExceptionPublisher = buildPublisher(
async (notification, handlers) => {
for (const handler of handlers) {
await handler(notification);
}
},
);
const publishers: Record<PublishStrategy, IPublisher> = {
[PublishStrategy.ParallelNoWait]: parallelNoWaitPublisher,
[PublishStrategy.ParallelWhenAny]: parallelWhenAnyPublisher,
[PublishStrategy.ParallelWhenAll]: parallelWhenAllPublisher,
[PublishStrategy.Async]: parallelWhenAllPublisher,
[PublishStrategy.SyncContinueOnException]: syncContinueOnExceptionPublisher,
[PublishStrategy.SyncStopOnException]: syncStopOnExceptionPublisher,
};
export class PublisherFactory {
static create(publishStrategy: PublishStrategy): IPublisher {
const publisher = publishers[publishStrategy];
if (publisher == null) {
throw new Error(`Invalid publish strategy`);
}
return publisher;
}
}