From f9cfada8409b3a88323dafa80730c5565c067da8 Mon Sep 17 00:00:00 2001 From: Blake Matthes Date: Sat, 1 Nov 2025 00:05:25 -0500 Subject: [PATCH] feat(listeners): added in a new feature to auto add new listeners --- app/src/internal/system/utlis/addListeners.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 app/src/internal/system/utlis/addListeners.ts diff --git a/app/src/internal/system/utlis/addListeners.ts b/app/src/internal/system/utlis/addListeners.ts new file mode 100644 index 0000000..c4b9745 --- /dev/null +++ b/app/src/internal/system/utlis/addListeners.ts @@ -0,0 +1,51 @@ +import { Client } from "pg"; +import { createLogger } from "../../../pkg/logger/logger.js"; + +export const addListeners = async () => { + const log = createLogger({ module: "utils", subModule: "listeners" }); + const client = new Client({ + connectionString: process.env.DATABASE_URL_V1, + }); + + await client.connect(); + + try { + log.info({}, "Running the new log listener"); + await client.query(` + CREATE OR REPLACE FUNCTION notify_new_log() + RETURNS trigger AS $$ + BEGIN + PERFORM pg_notify('logs_channel', row_to_json(NEW)::text); + RETURN NEW; + END; + $$ LANGUAGE plpgsql; + + CREATE TRIGGER logs_notify_trigger + AFTER INSERT ON logs + FOR EACH ROW + EXECUTE FUNCTION notify_new_log(); + `); + } catch (e) { + log.info({}, "log listener exist"); + } + + try { + log.info({}, "Running the new label listener"); + await client.query(` + CREATE OR REPLACE FUNCTION notify_new_label() + RETURNS trigger AS $$ + BEGIN + PERFORM pg_notify('label_channel', row_to_json(NEW)::text); + RETURN NEW; + END; + $$ LANGUAGE plpgsql; + + CREATE TRIGGER label_notify_trigger + AFTER INSERT ON prodlabels + FOR EACH ROW + EXECUTE FUNCTION notify_new_label(); + `); + } catch (e) { + log.info({}, "label listener exists"); + } +};