91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
/**
|
|
* @fileoverview REST Hook subscription storage.
|
|
* @module store/webhooks
|
|
*/
|
|
|
|
import { randomUUID } from 'node:crypto';
|
|
import { getStore, persist } from './db.js';
|
|
import { createDebugger } from '../debug/logger.js';
|
|
|
|
const log = createDebugger('webhooks');
|
|
|
|
/**
|
|
* @typedef {Object} Webhook
|
|
* @property {string} id
|
|
* @property {string} tenantId
|
|
* @property {string} targetUrl
|
|
* @property {string} event
|
|
* @property {string} createdAt
|
|
*/
|
|
|
|
/**
|
|
* @param {object} params
|
|
* @param {string} params.tenantId
|
|
* @param {string} params.targetUrl
|
|
* @param {string} params.event
|
|
* @returns {Webhook}
|
|
*/
|
|
export function createWebhook({ tenantId, targetUrl, event }) {
|
|
/** @type {Webhook} */
|
|
const hook = {
|
|
id: randomUUID(),
|
|
tenantId,
|
|
targetUrl,
|
|
event,
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
|
|
const store = getStore();
|
|
store.webhooks.push(hook);
|
|
persist();
|
|
log.info('webhook created', { hookId: hook.id, tenantId, event });
|
|
return hook;
|
|
}
|
|
|
|
/**
|
|
* Delete a webhook for a tenant by id and/or targetUrl.
|
|
*
|
|
* @param {object} params
|
|
* @param {string} params.tenantId
|
|
* @param {string} [params.hookId]
|
|
* @param {string} [params.targetUrl]
|
|
* @returns {boolean} True if at least one webhook was removed.
|
|
*/
|
|
export function deleteWebhook({ tenantId, hookId, targetUrl }) {
|
|
if (!hookId && !targetUrl) return false;
|
|
|
|
const store = getStore();
|
|
const before = store.webhooks.length;
|
|
|
|
store.webhooks = store.webhooks.filter((hook) => {
|
|
if (hook.tenantId !== tenantId) return true;
|
|
if (hookId && hook.id === hookId) return false;
|
|
if (!hookId && targetUrl && hook.targetUrl === targetUrl) return false;
|
|
return true;
|
|
});
|
|
|
|
const removedCount = before - store.webhooks.length;
|
|
if (removedCount > 0) {
|
|
persist();
|
|
log.info('webhook deleted', { tenantId, hookId, removedCount });
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* @param {string} tenantId
|
|
* @param {string} event
|
|
* @returns {Webhook[]}
|
|
*/
|
|
export function getActiveWebhooks(tenantId, event) {
|
|
return getStore().webhooks.filter((h) => h.tenantId === tenantId && h.event === event);
|
|
}
|
|
|
|
/**
|
|
* @param {string} tenantId
|
|
* @returns {Webhook[]}
|
|
*/
|
|
export function listWebhooksForTenant(tenantId) {
|
|
return getStore().webhooks.filter((h) => h.tenantId === tenantId);
|
|
}
|