import { Command } from 'commander'; import path from 'path'; import fs from 'fs'; import { normalizeName, searchConnection, } from '../../../../helpers/profileGeneratorHelper'; import { v4 } from 'uuid'; import { webhookYaml } from '../../../../components/webhookTemplate'; import { getProjectPath } from '../../../../helpers/cluserHelper'; import { mergeVariables, readVariableValue, } from '../../../../helpers/variablesHelper'; export function GenerateWebhookCommand(): Command { const cmd = new Command('generate') .alias('g') .description('Generates a HexaSync Webhook based on a specific connection') .option( '-c, --connection-name ', 'Search for related connection, e.g.: Shopify, QuickBooks', ) .action(async ({ connectionName }) => { const connection: any = await searchConnection(connectionName); if (!connection) { console.error(`There is no such connection ${connectionName}`); return; } const normalizedName = normalizeName( String(readVariableValue(connection.name) || ''), ); const webhookVariableKey = `${normalizedName.camelCaseName}_Webhook`; let webhookYml = webhookYaml(); const webhookVariables = [ { field: 'id', key: `**${webhookVariableKey}_Id**`, value: v4(), }, { field: 'name', key: `**${webhookVariableKey}_Name**`, value: normalizedName.displayName, }, { field: 'connectionId', key: connection.id, value: '', doNotMerge: true, }, ]; for (var i = 0; i < webhookVariables.length; i++) { var variable = webhookVariables[i]; webhookYml = webhookYml.replaceAll( `||VARIABLE_KEY_${variable.field}||`, variable.key, ); } mergeVariables(webhookVariables.filter((x) => !x.doNotMerge)); const componentPath = getProjectPath(); const webhookFilePath = path.join( componentPath, 'webhooks', `${webhookVariableKey}.yaml`, ); if (fs.existsSync(webhookFilePath)) { console.error(`There is a file exists in ${webhookFilePath}`); return; } fs.writeFileSync(webhookFilePath, webhookYml); }); return cmd; }