import { Knex } from 'knex' import { Webhook } from '@/modules/webhooks/domain/types' import { CountWebhooksByStreamId, CreateWebhook, GetWebhookById, UpdateWebhook } from '@/modules/webhooks/domain/operations' type WebhookConfig = Omit & { triggers: Record } const tables = (db: Knex) => ({ webhooksConfigs: db('webhooks_config'), webhooksEvents: db('webhooks_events') }) const toTriggersObj = (triggers: string[]): Record => triggers.reduce((acc, trigger) => ({ ...acc, [trigger]: true }), {}) const toTriggersArray = (triggers: Record): string[] => Object.keys(triggers) export const createWebhookFactory = ({ db }: { db: Knex }): CreateWebhook => async ({ id, streamId, url, description, secret, enabled, triggers }) => { const triggersObj = toTriggersObj(triggers) const [{ id: webhookId }] = await tables(db) .webhooksConfigs.insert({ id, streamId, url, description, secret, enabled, triggers: triggersObj }) .returning('id') return webhookId } export const countWebhooksByStreamIdFactory = ({ db }: { db: Knex }): CountWebhooksByStreamId => async ({ streamId }) => { const [res] = await tables(db).webhooksConfigs.where({ streamId }).count() return parseInt(res.count.toString()) } export const getWebhookByIdFactory = ({ db }: { db: Knex }): GetWebhookById => async ({ id }) => { const webhook = await tables(db).webhooksConfigs.select('*').where({ id }).first() if (!webhook) { return null } return { ...webhook, triggers: toTriggersArray(webhook.triggers) } } export const updateWebhookFactory = ({ db }: { db: Knex }): UpdateWebhook => async ({ webhookId, webhookInput }) => { const { triggers, ...update } = webhookInput let triggersObj: Record | undefined if (triggers) { triggersObj = toTriggersObj(triggers) } await tables(db) .webhooksConfigs.where({ id: webhookId }) .update({ ...update, triggers: triggersObj }) return webhookId }