@sentzunhat/zacatl
Version:
A modular, high-performance TypeScript microservice framework for Node.js, featuring layered architecture, dependency injection, and robust validation for building scalable APIs and distributed systems.
65 lines • 2.72 kB
JavaScript
import '../third-party/reflect-metadata.js';
import { InternalServerError } from '../error/index.js';
import { container as tsyringeContainer } from '../third-party/tsyringe.js';
export const getContainer = () => {
return tsyringeContainer;
};
export const registerDependency = (token, implementation) => {
tsyringeContainer.register(token, { useClass: implementation });
};
export const registerSingleton = (token, implementation) => {
tsyringeContainer.registerSingleton(token, implementation);
};
export const registerValue = (token, value) => {
tsyringeContainer.register(token, { useValue: value });
};
export const resolveDependency = (token) => {
return tsyringeContainer.resolve(token);
};
export const clearContainer = () => {
tsyringeContainer.clearInstances();
tsyringeContainer.reset();
};
export const resolveDependencies = (dependencies) => {
return dependencies.map((dependency) => {
if (!tsyringeContainer.isRegistered(dependency)) {
const name = dependency.name ?? String(dependency);
throw new InternalServerError({
message: `Failed to resolve '${name}' from the DI container`,
reason: 'Make sure the class is decorated with @injectable() (or @singleton()) ' +
'and is registered before resolution. ' +
"If this class is a repository, ensure it is listed under 'layers.infrastructure.repositories'. " +
"If it is a domain service, ensure it is listed under 'layers.domain.providers'.",
component: 'DIContainer',
operation: 'resolveDependencies',
metadata: { dependencyName: name },
});
}
try {
return tsyringeContainer.resolve(dependency);
}
catch (err) {
const name = dependency.name ?? String(dependency);
throw new InternalServerError({
message: `Failed to resolve '${name}' from the DI container`,
reason: err instanceof Error ? err.message : String(err),
component: 'DIContainer',
operation: 'resolveDependencies',
metadata: { dependencyName: name },
error: err instanceof Error ? err : undefined,
});
}
});
};
export const registerDependencies = (dependencies) => {
for (const dependency of dependencies) {
tsyringeContainer.register(dependency, {
useClass: dependency,
});
}
};
export const registerAndResolve = (dependencies) => {
registerDependencies(dependencies);
return resolveDependencies(dependencies);
};
//# sourceMappingURL=container.js.map