@expressots/core
Version:
Expressots - modern, fast, lightweight nodejs web framework (@core)
93 lines (92 loc) • 3.42 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProviderManager = void 0;
const inversify_1 = require("../di/inversify");
const logger_provider_1 = require("./logger/logger.provider");
/**
* ProviderManager Class - A class for managing dependency injection providers.
* @public API
*/
class ProviderManager {
constructor(container) {
this.logger = new logger_provider_1.Logger();
this.container = container;
}
/**
* Register a provider with the container.
* @public API
*/
register(serviceIdentifier, constructorOrScope, scope = inversify_1.BindingScopeEnum.Request) {
if (this.container.isBound(serviceIdentifier)) {
this.logger.warn(`${serviceIdentifier.name} already registered`, "provider-manager");
return;
}
let binding;
if (typeof constructorOrScope === "function") {
// Overload where constructor is provided
const constructor = constructorOrScope;
const scopeDefinition = scope || inversify_1.BindingScopeEnum.Transient;
binding = this.container.bind(serviceIdentifier).to(constructor);
this.applyScope(binding, scopeDefinition);
}
else {
const scopeDefinition = constructorOrScope ||
inversify_1.BindingScopeEnum.Transient;
binding = this.container.bind(serviceIdentifier).toSelf();
this.applyScope(binding, scopeDefinition);
}
}
/**
* Get a provider from the container.
* @param serviceIdentifier - The service identifier to get from the container.
* @returns An instance of the provider.
* @public API
*/
get(serviceIdentifier) {
if (!this.container.isBound(serviceIdentifier)) {
this.logger.error(`${this.getServiceIdentifierName(serviceIdentifier)} not registered`, "ProviderManager");
throw new Error(`Provider ${this.getServiceIdentifierName(serviceIdentifier)} not registered`);
}
return this.container.get(serviceIdentifier);
}
/**
* Apply the scope to the binding.
* @param binding - The binding to apply the scope to.
* @param scope - The scope to apply.
* @private
*/
applyScope(binding, scope) {
switch (scope) {
case inversify_1.BindingScopeEnum.Singleton:
binding.inSingletonScope();
break;
case inversify_1.BindingScopeEnum.Request:
binding.inRequestScope();
break;
case inversify_1.BindingScopeEnum.Transient:
default:
binding.inTransientScope();
break;
}
}
/**
* Get the name of the service identifier for logging purposes.
* @param serviceIdentifier - The service identifier.
* @returns The name of the service identifier.
* @private
*/
getServiceIdentifierName(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
serviceIdentifier) {
if (typeof serviceIdentifier === "function") {
return serviceIdentifier.name;
}
else if (typeof serviceIdentifier === "symbol") {
return serviceIdentifier.toString();
}
else {
return serviceIdentifier;
}
}
}
exports.ProviderManager = ProviderManager;
;