2024-06-05 08:52:41 +02:00
|
|
|
import { db } from "@link-stack/bridge-common";
|
2025-11-21 14:55:28 +01:00
|
|
|
import { createLogger } from "@link-stack/logger";
|
|
|
|
|
|
|
|
|
|
const logger = createLogger('notify-webhooks');
|
2024-04-30 13:13:49 +02:00
|
|
|
|
|
|
|
|
export interface NotifyWebhooksOptions {
|
|
|
|
|
backendId: string;
|
|
|
|
|
payload: any;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const notifyWebhooksTask = async (
|
|
|
|
|
options: NotifyWebhooksOptions,
|
|
|
|
|
): Promise<void> => {
|
|
|
|
|
const { backendId, payload } = options;
|
2025-11-21 14:55:28 +01:00
|
|
|
|
|
|
|
|
logger.debug({
|
|
|
|
|
backendId,
|
|
|
|
|
payloadKeys: Object.keys(payload),
|
|
|
|
|
}, 'Processing webhook notification');
|
2024-04-30 13:13:49 +02:00
|
|
|
|
|
|
|
|
const webhooks = await db
|
|
|
|
|
.selectFrom("Webhook")
|
|
|
|
|
.selectAll()
|
|
|
|
|
.where("backendId", "=", backendId)
|
|
|
|
|
.execute();
|
|
|
|
|
|
2025-11-21 14:55:28 +01:00
|
|
|
logger.debug({ count: webhooks.length, backendId }, 'Found webhooks');
|
|
|
|
|
|
2024-04-30 13:13:49 +02:00
|
|
|
for (const webhook of webhooks) {
|
|
|
|
|
const { endpointUrl, httpMethod, headers } = webhook;
|
|
|
|
|
const finalHeaders = { "Content-Type": "application/json", ...headers };
|
2025-11-21 14:55:28 +01:00
|
|
|
const body = JSON.stringify(payload);
|
|
|
|
|
|
|
|
|
|
logger.debug({
|
|
|
|
|
url: endpointUrl,
|
2024-04-30 13:13:49 +02:00
|
|
|
method: httpMethod,
|
2025-11-21 14:55:28 +01:00
|
|
|
bodyLength: body.length,
|
|
|
|
|
headerKeys: Object.keys(finalHeaders),
|
|
|
|
|
}, 'Sending webhook');
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const result = await fetch(endpointUrl, {
|
|
|
|
|
method: httpMethod,
|
|
|
|
|
headers: finalHeaders,
|
|
|
|
|
body,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
logger.debug({
|
|
|
|
|
url: endpointUrl,
|
|
|
|
|
status: result.status,
|
|
|
|
|
statusText: result.statusText,
|
|
|
|
|
ok: result.ok,
|
|
|
|
|
}, 'Webhook response');
|
|
|
|
|
|
|
|
|
|
if (!result.ok) {
|
|
|
|
|
const responseText = await result.text();
|
|
|
|
|
logger.error({
|
|
|
|
|
url: endpointUrl,
|
|
|
|
|
status: result.status,
|
|
|
|
|
responseSample: responseText.substring(0, 500),
|
|
|
|
|
}, 'Webhook error response');
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
logger.error({
|
|
|
|
|
url: endpointUrl,
|
|
|
|
|
error: error instanceof Error ? error.message : error,
|
|
|
|
|
}, 'Webhook request failed');
|
|
|
|
|
}
|
2024-04-30 13:13:49 +02:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default notifyWebhooksTask;
|