import { Command } from 'commander'; import fs from 'fs'; import { findConnection, normalizeName, searchWebhook, } from '../../../../helpers/profileGeneratorHelper'; import { v4 } from 'uuid'; import { webhookEventYaml } from '../../../../components/webhookTemplate'; import { parse, stringify } from 'yaml'; import { mergeVariables, readVariableValue, } from '../../../../helpers/variablesHelper'; export function GenerateWebhookEventCommand(): Command { const cmd = new Command('add-event') .alias('ae') .description( 'Generates a HexaSync Webhook Event based on a specific connection', ) .option( '-w, --webhook-name ', 'Search for related webhook, e.g.: Shopify, QuickBooks', ) .option( '-e, --event-name ', "The event name, e.g.: 'product created', 'sales order updated'", ) .action(async ({ webhookName, eventName }) => { const webhookYml: any = await searchWebhook(webhookName); if (!webhookYml?.connectionId) { console.error(`The webhook is missing connectionId`); return; } const connectionYml: any = findConnection(webhookYml.connectionId); const normalizedConnectionName = normalizeName( String(readVariableValue(connectionYml.name) || ''), ); const normalizedEventName = normalizeName(eventName); const webhookEventVariableKey = `${normalizedConnectionName.camelCaseName}_${normalizedEventName.camelCaseName}_Webhook_Event`; const webhookEventTargetKey = `${normalizedEventName.underscoreSlug.toUpperCase()}`; let webhookEventYml: any = webhookEventYaml(); const webhookEventVariables = [ { field: 'id', key: `**${webhookEventVariableKey}_Id**`, value: v4(), }, ]; for (var i = 0; i < webhookEventVariables.length; i++) { var variable = webhookEventVariables[i]; webhookEventYml = webhookEventYml.replaceAll( `||VARIABLE_KEY_${variable.field}||`, variable.key, ); } if (!!webhookYml.targets && !!webhookYml.targets[webhookEventTargetKey]) { console.error( 'There is an event with the same name has already registered.', ); return; } webhookYml.targets = { ...webhookYml.targets, [webhookEventTargetKey]: { ...parse(webhookEventYml) }, }; const webhookFilePath = webhookYml.__file_path; delete webhookYml.__real_name; delete webhookYml.__file_path; mergeVariables(webhookEventVariables); fs.writeFileSync( webhookFilePath, stringify( { webhooks: [webhookYml] }, { keepSourceTokens: true, lineWidth: 0 }, ), ); console.log( 'Remember to add webhook listener and the event matching patterns to match your business', ); }); return cmd; }