link-stack/apps/bridge-worker/tasks/common/notify-webhooks.ts
2025-07-07 20:02:54 +02:00

71 lines
1.9 KiB
TypeScript

import { db } from "@link-stack/bridge-common";
export interface NotifyWebhooksOptions {
backendId: string;
payload: any;
}
const notifyWebhooksTask = async (
options: NotifyWebhooksOptions,
): Promise<void> => {
const { backendId, payload } = options;
console.log(`[notify-webhooks] Processing webhook notification:`, {
backendId,
payloadKeys: Object.keys(payload),
payload: JSON.stringify(payload, null, 2),
});
const webhooks = await db
.selectFrom("Webhook")
.selectAll()
.where("backendId", "=", backendId)
.execute();
console.log(`[notify-webhooks] Found ${webhooks.length} webhooks for backend ${backendId}`);
for (const webhook of webhooks) {
const { endpointUrl, httpMethod, headers } = webhook;
const finalHeaders = { "Content-Type": "application/json", ...headers };
const body = JSON.stringify(payload);
console.log(`[notify-webhooks] Sending webhook:`, {
url: endpointUrl,
method: httpMethod,
bodyLength: body.length,
headers: Object.keys(finalHeaders),
payload: body,
});
try {
const result = await fetch(endpointUrl, {
method: httpMethod,
headers: finalHeaders,
body,
});
console.log(`[notify-webhooks] Webhook response:`, {
url: endpointUrl,
status: result.status,
statusText: result.statusText,
ok: result.ok,
});
if (!result.ok) {
const responseText = await result.text();
console.error(`[notify-webhooks] Webhook error response:`, {
url: endpointUrl,
status: result.status,
response: responseText.substring(0, 500), // First 500 chars
});
}
} catch (error) {
console.error(`[notify-webhooks] Webhook request failed:`, {
url: endpointUrl,
error: error instanceof Error ? error.message : error,
});
}
}
};
export default notifyWebhooksTask;