ReferenceDescriptor.ts
68 lines
| 1.9 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r120 | import { argumentNotEmptyString, each } from "../safe"; | ||
|
|
r49 | import { ActivationContext } from "./ActivationContext"; | ||
|
|
r133 | import { Descriptor, PartialServiceMap, TypeOfService, ContainerKeys } from "./interfaces"; | ||
|
|
r49 | |||
|
|
r120 | export interface ReferenceDescriptorParams<S extends object, K extends ContainerKeys<S>> { | ||
|
|
r113 | name: K; | ||
|
|
r49 | optional?: boolean; | ||
|
|
r133 | default?: TypeOfService<S, K>; | ||
|
|
r115 | services?: PartialServiceMap<S>; | ||
|
|
r49 | } | ||
|
|
r120 | export class ReferenceDescriptor<S extends object = any, K extends ContainerKeys<S> = ContainerKeys<S>> | ||
|
|
r133 | implements Descriptor<S, TypeOfService<S, K>> { | ||
|
|
r114 | |||
|
|
r113 | _name: K; | ||
|
|
r49 | |||
| _optional = false; | ||||
|
|
r133 | _default: TypeOfService<S, K> | undefined; | ||
|
|
r49 | |||
|
|
r118 | _services: PartialServiceMap<S>; | ||
|
|
r49 | |||
|
|
r113 | constructor(opts: ReferenceDescriptorParams<S, K>) { | ||
|
|
r49 | argumentNotEmptyString(opts && opts.name, "opts.name"); | ||
| this._name = opts.name; | ||||
| this._optional = !!opts.optional; | ||||
| this._default = opts.default; | ||||
|
|
r113 | |||
|
|
r120 | this._services = (opts.services || {}) as PartialServiceMap<S>; | ||
|
|
r49 | } | ||
|
|
r114 | activate(context: ActivationContext<S>) { | ||
|
|
r49 | // добавляем сервисы | ||
| if (this._services) { | ||||
|
|
r115 | each(this._services, (v, k) => context.register(k, v)); | ||
|
|
r49 | } | ||
|
|
r122 | const res = this._optional ? | ||
| context.resolve(this._name, this._default) : | ||||
| context.resolve(this._name); | ||||
|
|
r49 | |||
|
|
r122 | return res; | ||
|
|
r49 | } | ||
| toString() { | ||||
| const opts = []; | ||||
| if (this._optional) | ||||
| opts.push("optional"); | ||||
| const parts = [ | ||||
| "@ref " | ||||
| ]; | ||||
| if (opts.length) { | ||||
| parts.push("{"); | ||||
| parts.push(opts.join()); | ||||
| parts.push("} "); | ||||
| } | ||||
|
|
r113 | parts.push(this._name.toString()); | ||
|
|
r49 | |||
|
|
r115 | if (this._default !== undefined && this._default !== null) { | ||
|
|
r49 | parts.push(" = "); | ||
|
|
r115 | parts.push(String(this._default)); | ||
|
|
r49 | } | ||
| return parts.join(""); | ||||
| } | ||||
| } | ||||
