import { getNameOfServiceType } from "../helpers/getNameOfServiceType.js"; import type { IResolvedServiceImplementation, IServiceDescriptor, IServiceImplementationResolver, IServiceTypeResolver, RequestPath, } from "../types/index.js"; import { Debug } from "../debug.js"; import { BaseServiceImplementationResolver } from "./BaseServiceImplementationResolver.js"; import { AsyncServiceImplementationError } from "../di/errors/AsyncServiceImplementationError.js"; import { fallback } from "./fallback.js"; const NOT_LOADED = Symbol("NOT_LOADED"); export class AsyncServiceImplementationResolver< T, > extends BaseServiceImplementationResolver { get name(): string { if (this.implementation === NOT_LOADED) { //"lazy(?)" return Debug.errors.serviceNotLoaded(this.loader); } return getNameOfServiceType(this.implementation); } private implementation: IServiceImplementationResolver | typeof NOT_LOADED; private promise: Promise> | null; constructor( private loader: () => Promise>, ) { super(); this.implementation = NOT_LOADED; this.promise = null; } override *resolve( internalGetService: IServiceTypeResolver, descriptor: IServiceDescriptor, requestedBy: IServiceDescriptor | null, requestedPath: RequestPath, mode: "sync" | "async", context: Readonly>, ): Generator, IResolvedServiceImplementation, unknown> { if (this.implementation === NOT_LOADED || mode === "sync") { yield this.load(); if (this.implementation === NOT_LOADED) { throw new AsyncServiceImplementationError(); } } return (this.resolved = yield* this.implementation.resolve( internalGetService, descriptor, requestedBy, requestedPath, mode, context, )); } private async load(): Promise> { if (this.implementation !== NOT_LOADED) { return this.implementation; } if (!this.promise) { this.promise = this.loader() .then((implementation) => { this.implementation = fallback(implementation); return this.implementation; }) .finally(() => { this.promise = null; }); } return this.promise; } }