UNPKG

@elsikora/cladi

Version:

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

87 lines (84 loc) 2.83 kB
import { safeDeepClone } from '../../../application/utility/safe-deep-clone.utility.js'; import { BaseError } from './error.class.js'; import { ConsoleLoggerService } from '../../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 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(cachedItem); } const template = this.REGISTRY.get(name); if (!template) { throw new BaseError("Template not found", { code: "TEMPLATE_NOT_FOUND", source: "Factory", }); } const result = this.TRANSFORMER ? this.TRANSFORMER(template) : safeDeepClone(template); this.CACHE.set(name, result); this.LOGGER.debug(`Created item: ${name}`, { source: "Factory" }); return safeDeepClone(result); } /** * Get the registry associated with this factory. * @returns {IRegistry<T>} The registry instance. */ getRegistry() { return this.REGISTRY; } } export { BaseFactory }; //# sourceMappingURL=factory.class.js.map