FluentConfiguration.ts
60 lines
| 2.0 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r135 | import { Container } from "../Container"; | ||
| import { argumentNotNull, each, isPrimitive, isPromise } from "../../safe"; | ||||
| import { DescriptorBuilder } from "./DescriptorBuilder"; | ||||
| import { RegistrationBuilder, FluentRegistrations } from "./interfaces"; | ||||
| import { Cancellation } from "../../Cancellation"; | ||||
| export class FluentConfiguration<S extends object, Y extends keyof S = keyof S> { | ||||
| _builders: { [k in keyof S]?: RegistrationBuilder<S, S[k]> } = {}; | ||||
| register<K extends Y>(name: K, builder: RegistrationBuilder<S, S[K]>): FluentConfiguration<S, Exclude<Y, K>>; | ||||
| register<K extends Y>(config: FluentRegistrations<K, S>): FluentConfiguration<S, Exclude<Y, K>>; | ||||
| register<K extends Y>(nameOrConfig: K | FluentRegistrations<K, S>, builder?: RegistrationBuilder<S, S[K]>): FluentConfiguration<S, Exclude<Y, K>> { | ||||
| if (isPrimitive(nameOrConfig)) { | ||||
| argumentNotNull(builder, "builder"); | ||||
| this._builders[nameOrConfig] = builder; | ||||
| } else { | ||||
| each(nameOrConfig, (v, k) => this.register(k, v)); | ||||
| } | ||||
| return this; | ||||
| } | ||||
|
|
r136 | apply<SC extends object>(target: Container<SC>, ct = Cancellation.none) { | ||
|
|
r135 | |||
| let pending = 1; | ||||
|
|
r136 | const _t2 = target as unknown as Container<SC & S>; | ||
| return new Promise<Container<SC & S>>((resolve, reject) => { | ||||
|
|
r135 | function guard(v: void | Promise<void>) { | ||
| if (isPromise(v)) | ||||
| v.catch(reject); | ||||
| } | ||||
| function complete() { | ||||
| if (!--pending) | ||||
|
|
r136 | resolve(_t2); | ||
|
|
r135 | } | ||
| each(this._builders, (v, k) => { | ||||
| pending++; | ||||
|
|
r136 | const d = new DescriptorBuilder<SC & S, any>(_t2, | ||
|
|
r135 | result => { | ||
|
|
r136 | _t2.register(k, result); | ||
|
|
r135 | complete(); | ||
| }, | ||||
| reject | ||||
| ); | ||||
| try { | ||||
| guard(v(d, ct)); | ||||
| } catch (e) { | ||||
| reject(e); | ||||
| } | ||||
| }); | ||||
| complete(); | ||||
| }); | ||||
| } | ||||
| } | ||||
