Refactoring 3

This commit is contained in:
Darren Clarke 2024-04-30 13:13:49 +02:00
parent e4b78ceec2
commit d1fb9b4d06
20 changed files with 201 additions and 123 deletions

View file

@ -1,57 +0,0 @@
import Wreck from "@hapi/wreck";
import * as R from "remeda";
import { withDb, AppDatabase } from "../../lib/db";
// import logger from "../logger";
export interface WebhookOptions {
webhookId: string;
payload: any;
}
const notifyWebhooksTask = async (options: WebhookOptions): Promise<void> =>
withDb(async (db: AppDatabase) => {
const { webhookId, payload } = options;
const webhook = await db.webhooks.findById({ id: webhookId });
if (!webhook) {
// logger.debug(
// { webhookId },
// "notify-webhook: no webhook registered with id",
// );
return;
}
const { endpointUrl, httpMethod, headers } = webhook;
const headersFormatted = R.reduce(
headers || [],
(acc: any, h: any) => {
acc[h.header] = h.value;
return acc;
},
{},
);
const wreck = Wreck.defaults({
json: true,
headers: headersFormatted,
});
// http errors will bubble up and cause the job to fail and be retried
try {
// logger.debug(
// { webhookId, endpointUrl, httpMethod },
// "notify-webhook: notifying",
// );
await (httpMethod === "post"
? wreck.post(endpointUrl, { payload })
: wreck.put(endpointUrl, { payload }));
} catch (error: any) {
// logger.error(
// { webhookId, error: error.output },
// "notify-webhook failed with this error",
// );
throw new Error(`webhook failed webhookId=${webhookId}`);
}
});
export default notifyWebhooksTask;

View file

@ -0,0 +1,31 @@
import { db } from "bridge-common";
export interface NotifyWebhooksOptions {
backendId: string;
payload: any;
}
const notifyWebhooksTask = async (
options: NotifyWebhooksOptions,
): Promise<void> => {
const { backendId, payload } = options;
const webhooks = await db
.selectFrom("Webhook")
.selectAll()
.where("backendId", "=", backendId)
.execute();
for (const webhook of webhooks) {
const { endpointUrl, httpMethod, headers } = webhook;
const finalHeaders = { "Content-Type": "application/json", ...headers };
await fetch(endpointUrl, {
method: httpMethod,
headers: finalHeaders,
body: JSON.stringify(payload),
});
}
};
export default notifyWebhooksTask;