fix(webhooks): harden event parsing and await dispatch results
swadhinbiswas committed 8 months ago
0d21323
1 parent df5baca
commit 0d21323
1 file changed
+15 -9
Showing 1 changed file+15-9
▼src/lib/webhooks.ts
+15-9
| @@ -34,7 +34,13 @@ export async function triggerWebhooks( | ||
34 | 34 | |
35 | 35 | // Filter webhooks that subscribe to this event |
36 | 36 | const matchingWebhooks = webhooks.filter((hook) => { |
37 | - const events = Array.isArray(hook.events) ? hook.events : JSON.parse(hook.events as any); | |
37 | + let events: string[] = []; | |
38 | + try { | |
39 | + events = Array.isArray(hook.events) ? hook.events : JSON.parse(String(hook.events)); | |
40 | + } catch { | |
41 | + logger.warn({ webhookId: hook.id }, "Skipping webhook with invalid events config"); | |
42 | + return false; | |
43 | + } | |
38 | 44 | return events.includes(event) || events.includes("*"); |
39 | 45 | }); |
40 | 46 | |
| @@ -45,14 +51,14 @@ export async function triggerWebhooks( | ||
45 | 51 | "Triggering webhooks" |
46 | 52 | ); |
47 | 53 | |
48 | - // Dispatch to all matching webhooks (fire and forget) | |
49 | - // In a real system, this would go to a job queue (BullMQ/Redis) | |
50 | - // For now, we'll run it asynchronously | |
51 | - matchingWebhooks.forEach((hook) => { | |
52 | - dispatchWebhook(hook, event, payload).catch((err) => { | |
53 | - logger.error({ webhookId: hook.id, err }, "Failed to dispatch webhook"); | |
54 | - }); | |
55 | - }); | |
54 | + const results = await Promise.allSettled( | |
55 | + matchingWebhooks.map((hook) => dispatchWebhook(hook, event, payload)) | |
56 | + ); | |
57 | + | |
58 | + const failures = results.filter((result) => result.status === "rejected").length; | |
59 | + if (failures > 0) { | |
60 | + logger.warn({ repositoryId, event, failures }, "Some webhook dispatches failed"); | |
61 | + } | |
56 | 62 | } |
57 | 63 | |
58 | 64 | /** |
59 | 65 | |