-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathreceive.ts
97 lines (78 loc) · 2.37 KB
/
receive.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
// @ts-ignore to address #245
import AggregateError from "aggregate-error";
import { EmitterEventWebhookPayloadMap } from "../generated/get-webhook-payload-type-from-event";
import type {
EmitterWebhookEvent,
EmitterWebhookEventName,
State,
WebhookError,
WebhookEventHandlerError,
} from "../types";
import { wrapErrorHandler } from "./wrap-error-handler";
type EventAction = Extract<
EmitterEventWebhookPayloadMap[keyof EmitterEventWebhookPayloadMap],
{ action: string }
>["action"];
function getHooks(
state: State,
eventPayloadAction: EventAction | null,
eventName: EmitterWebhookEventName
): Function[] {
const hooks = [state.hooks[eventName], state.hooks["*"]];
if (eventPayloadAction) {
hooks.unshift(state.hooks[`${eventName}.${eventPayloadAction}`]);
}
return ([] as Function[]).concat(...hooks.filter(Boolean));
}
// main handler function
export function receiverHandle(state: State, event: EmitterWebhookEvent) {
const errorHandlers = state.hooks.error || [];
if (event instanceof Error) {
const error = Object.assign(new AggregateError([event]), {
event,
errors: [event],
});
errorHandlers.forEach((handler) => wrapErrorHandler(handler, error));
return Promise.reject(error);
}
if (!event || !event.name) {
throw new AggregateError(["Event name not passed"]);
}
if (!event.payload) {
throw new AggregateError(["Event payload not passed"]);
}
// flatten arrays of event listeners and remove undefined values
const hooks = getHooks(
state,
"action" in event.payload ? event.payload.action : null,
event.name
);
if (hooks.length === 0) {
return Promise.resolve();
}
const errors: WebhookError[] = [];
const promises = hooks.map((handler: Function) => {
let promise = Promise.resolve(event);
if (state.transform) {
// @ts-expect-error
promise = promise.then(state.transform);
}
return promise
.then((event) => {
return handler(event);
})
.catch((error) => errors.push(Object.assign(error, { event })));
});
return Promise.all(promises).then(() => {
if (errors.length === 0) {
return;
}
const error = new AggregateError(errors) as WebhookEventHandlerError;
Object.assign(error, {
event,
errors,
});
errorHandlers.forEach((handler) => wrapErrorHandler(handler, error));
throw error;
});
}