typescript-scaffolder
Version:
 ### Unit Test Coverage: 97.12%
123 lines (121 loc) • 5.24 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateWebhookRegistry = generateWebhookRegistry;
exports.getWebhookFunction = getWebhookFunction;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const logger_1 = require("../utils/logger");
const file_system_1 = require("../utils/file-system");
/**
* Creates a registry of webhook functions within a file that can be used at runtime.
* This function will produce an object in the following shape,
* where the field name equals the folder name where the webhook files are located
*
* Example:
* export const webhookRegistry = {
* 'source-charlie': {
* ...handle_payment_webhook
* },
* 'source-delta': {
* ...send_notification_webhook
* }
* };
*
* @param webhookRootDir - the parent directory where the webhook files are located. Will go into child directories
* @param registryFileName - the name of the registry file
*/
async function generateWebhookRegistry(webhookRootDir, registryFileName = 'registry.ts') {
const funcName = 'generateWebhookRegistry';
logger_1.Logger.debug(funcName, 'Generating webhook registry...');
const importMap = new Map(); // Map<subdirectory, filePaths>
(0, file_system_1.walkDirectory)(webhookRootDir, (filePath) => {
if (filePath.endsWith('.ts') && !filePath.endsWith(registryFileName)) {
const subDir = path.relative(webhookRootDir, path.dirname(filePath));
const files = importMap.get(subDir) || [];
files.push(filePath);
importMap.set(subDir, files);
}
}, '.ts');
if (importMap.size === 0) {
logger_1.Logger.warn(funcName, 'No webhook files found. Registry will not be generated.');
return;
}
const importStatements = [];
const registryEntries = [];
for (const [subDir, files] of importMap.entries()) {
const registryKey = subDir.replace(/\\/g, '/'); // Normalize Windows paths
const entryLines = [];
for (const file of files) {
const fileName = path.basename(file, '.ts');
const importVar = `${fileName.replace(/[^a-zA-Z0-9_$]/g, '_')}`;
const relativePath = `./${path.join(subDir, fileName).replace(/\\/g, '/')}`;
importStatements.push(`import * as ${importVar} from '${relativePath}';`);
entryLines.push(`...${importVar}`);
}
registryEntries.push(` '${registryKey}': {\n ${entryLines.join(',\n ')}\n }`);
}
const output = `${importStatements.join('\n')}
export const webhookRegistry = {
${registryEntries.join(',\n')}
};
`;
const registryPath = path.join(webhookRootDir, registryFileName);
fs.writeFileSync(registryPath, output, 'utf8');
}
/**
* Dynamically retrieves a webhook function from the generated registry.
*
* @param webhookRegistry - A nested record of namespace -> function name -> webhook function.
* @param service - The top-level key representing a group of webhook handlers (e.g. a source system).
* @param functionName - The exported name of the function within the selected service.
* @returns The referenced webhook function.
* @throws If the function or service cannot be found in the registry.
*/
function getWebhookFunction(webhookRegistry, service, functionName) {
const funcName = 'getWebhookFunction';
logger_1.Logger.debug(funcName, 'Fetching webhook function...');
const serviceRegistry = webhookRegistry?.[service];
if (!serviceRegistry) {
logger_1.Logger.warn(funcName, 'No service registry found.');
}
const fn = serviceRegistry?.[functionName];
if (!fn || typeof fn !== 'function') {
const msg = `Function "${functionName}" not found in service "${service}".`;
logger_1.Logger.error(funcName, msg);
throw new Error(msg);
}
return fn;
}
;