UNPKG

@elsikora/cladi

Version:

ClaDI is a library for creating and managing classes in TypeScript.

89 lines (85 loc) 2.96 kB
'use strict'; var safeDeepClone_utility = require('../../../application/utility/safe-deep-clone.utility.js'); var error_class = require('./error.class.js'); var consoleLogger_service = require('../../service/console-logger.service.js'); /** * Generic factory implementation that creates items by name using a registry as data source. * @template T The type of items created by the factory. * @see {@link https://elsikora.com/docs/cladi/core-concepts/factory} */ class BaseFactory { /** * Internal cache of created items. */ CACHE; /** * Logger instance. */ LOGGER; /** * Registry instance. */ REGISTRY; /** * Optional custom transformer function. */ TRANSFORMER; /** * Create a new factory instance. * @param {IBaseFactoryOptions<T>} options Factory options. */ constructor(options) { this.CACHE = new Map(); this.LOGGER = options.logger ?? new consoleLogger_service.ConsoleLoggerService(); this.REGISTRY = options.registry; this.TRANSFORMER = options.transformer; } /** * Clear all cached items or a specific cached item. * @param {string} [name] Optional name of specific cached item to clear. */ clearCache(name) { if (name) { this.CACHE.delete(name); this.LOGGER.debug(`Cache cleared for item: ${name}`, { source: "Factory" }); } else { this.CACHE.clear(); this.LOGGER.debug("Factory cache cleared", { source: "Factory" }); } } /** * Create an item by name. * @param {string} name The name of the item to create. * @returns {T} The created item. * @throws RegistryItemNotFoundError if no item with the given name exists in the registry. */ create(name) { this.LOGGER.debug(`Creating item: ${name}`, { source: "Factory" }); const cachedItem = this.CACHE.get(name); if (cachedItem) { this.LOGGER.debug(`Retrieved item from cache: ${name}`, { source: "Factory" }); return safeDeepClone_utility.safeDeepClone(cachedItem); } const template = this.REGISTRY.get(name); if (!template) { throw new error_class.BaseError("Template not found", { code: "TEMPLATE_NOT_FOUND", source: "Factory", }); } const result = this.TRANSFORMER ? this.TRANSFORMER(template) : safeDeepClone_utility.safeDeepClone(template); this.CACHE.set(name, result); this.LOGGER.debug(`Created item: ${name}`, { source: "Factory" }); return safeDeepClone_utility.safeDeepClone(result); } /** * Get the registry associated with this factory. * @returns {IRegistry<T>} The registry instance. */ getRegistry() { return this.REGISTRY; } } exports.BaseFactory = BaseFactory; //# sourceMappingURL=factory.class.js.map