@carlosv2/glue
Version:
Dependency injection library that stays out of the way
34 lines (33 loc) • 999 B
JavaScript
import { DiError } from '../error.js';
export class RunningContext {
constructor(container, stack = []) {
this.container = container;
this.stack = stack;
}
getContainer() {
return this.container;
}
isFrameInStack(type, id) {
for (const frame of this.stack) {
if (frame.type === type && frame.id === id) {
return true;
}
}
return false;
}
getRepresentation() {
return this.stack.map(frame => `${frame.type}(${frame.id})`).join(' -> ');
}
pushFrame(type, id) {
if (this.isFrameInStack(type, id)) {
throw new DiError(`Circular dependency detected: ${this.getRepresentation()} -> ${id}`);
}
return new RunningContext(this.container, [...this.stack, { type, id }]);
}
pushParameterFrame(id) {
return this.pushFrame('parameter', id);
}
pushServiceFrame(id) {
return this.pushFrame('service', id);
}
}