Enumeration: BindingScope

Scope for binding values

Members
Name Default Value Flags Description
CONTEXT "Context" exported

The binding provides a value as a singleton within each local context. The value is calculated only once per context and cached for subsequential uses. Child contexts have their own value and do not share with their ancestors.

For example, with the following context hierarchy:

  • app (with a binding 'b1' that produces sequential values 0, 1, ...)
    • req1
    • req2
  1. 0 is the resolved value for 'b1' within the app afterward
  • app.get('b1') ==> 0 (always)
  1. 'b1' is resolved in app but not in req1, a new value 1 is calculated and used for req1 afterward
  • req1.get('b1') ==> 1 (always)
  1. 'b1' is resolved in app but not in req2, a new value 2 is calculated and used for req2 afterward
  • req2.get('b1') ==> 2 (always)

SINGLETON "Singleton" exported

The binding provides a value as a singleton within the context hierarchy (the owning context and its descendants). The value is calculated only once for the owning context and cached for subsequential uses. Child contexts share the same value as their ancestors.

For example, with the following context hierarchy:

  • app (with a binding 'b1' that produces sequential values 0, 1, ...)
    • req1
    • req2
  1. 0 is the singleton for app afterward
  • app.get('b1') ==> 0 (always)
  1. 'b1' is resolved in app, reuse it for req1
  • req1.get('b1') ==> 0 (always)
  1. 'b1' is resolved in app, reuse it for req2
  • req2.get('b1') ==> 0 (always)

TRANSIENT "Transient" exported

The binding provides a value that is calculated each time. This will be the default scope if not set.

For example, with the following context hierarchy:

  • app (with a binding 'b1' that produces sequential values 0, 1, ...)
    • req1
    • req2

Now 'b1' is resolved to a new value each time for app and its descendants req1 and req2:

  • app.get('b1') ==> 0
  • req1.get('b1') ==> 1
  • req2.get('b1') ==> 2
  • req2.get('b1') ==> 3
  • app.get('b1') ==> 4

Enumeration: BindingType

Type of the binding source

Members
Name Default Value Flags Description
ALIAS "Alias" exported

A alias to another binding key with optional path

CLASS "Class" exported

A class to be instantiated as the value

CONSTANT "Constant" exported

A fixed value

DYNAMIC_VALUE "DynamicValue" exported

A function to get the value

PROVIDER "Provider" exported

A provider class with value() function to get the value

Class: binding = new Binding()

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

Properties
Name Type Default Value Flags Description
isLocked boolean public exported constructorProperty

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

key string public exported

Key of the binding

tagMap TagMap public exported

Map for tag name/value pairs

constructor(key: BindingAddress<T>, isLocked: boolean) : Binding

Parameters
Name Type Default Value Flags Description
key BindingAddress<T>

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

isLocked boolean false

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

scope() :

tagNames() :

type() :

valueConstructor() :

apply(templateFns: BindingTemplate<T>[]) : this

Apply one or more template functions to set up the binding with scope, tags, and other attributes as a group.

Parameters
Name Type Default Value Flags Description
templateFns BindingTemplate<T>[] rest

One or more functions to configure the binding

applyDefaultScope(scope: BindingScope) : this

Apply default scope to the binding. It only changes the scope if it's not set yet

Parameters
Name Type Default Value Flags Description
scope BindingScope

Default binding scope

getValue(ctx: Context, session: ResolutionSession) : ValueOrPromise<T>

This is an internal function optimized for performance. Users should use @inject(key) or ctx.get(key) instead.

Get the value bound to this key. Depending on isSync, this function returns either:

  • the bound value
  • a promise of the bound value

Consumers wishing to consume sync values directly should use isPromiseLike to check the type of the returned value to decide how to handle it.

Parameters
Name Type Default Value Flags Description
ctx Context

Context for the resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

getValue(ctx: Context, options: ResolutionOptions) : ValueOrPromise<T | undefined>

Returns a value or promise for this binding in the given context. The resolved value can be undefined if optional is set to true in options.

Parameters
Name Type Default Value Flags Description
ctx Context

Context for the resolution

options ResolutionOptions optional

Optional options for binding and dependency resolution

inScope(scope: BindingScope) : this

Set the binding scope

Parameters
Name Type Default Value Flags Description
scope BindingScope

Binding scope

lock() : this

Lock the binding so that it cannot be rebound

tag(tags: BindingTag[]) : this

Tag the binding with names or name/value objects. A tag has a name and an optional value. If not supplied, the tag name is used as the value.

Parameters
Name Type Default Value Flags Description
tags BindingTag[] rest

A list of names or name/value objects. Each parameter can be in one of the following forms:

  • string: A tag name without value
  • string[]: An array of tag names
  • TagMap: A map of tag name/value pairs

to(value: T) : this

Bind the key to a constant value. The value must be already available at binding time, it is not allowed to pass a Promise instance.

Parameters
Name Type Default Value Flags Description
value T

The bound value.

toAlias(keyWithPath: BindingAddress<T>) : this

Bind the key to an alias of another binding

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<T>

Target binding key with optional path, such as servers.RestServer.options#apiExplorer

toClass(ctor: Constructor<T>) : this

Bind the key to an instance of the given class.

Parameters
Name Type Default Value Flags Description
ctor Constructor<T>

The class constructor to call. Any constructor arguments must be annotated with @inject so that we can resolve them from the context.

toDynamicValue(factoryFn: () => ValueOrPromise<T>) : this

Bind the key to a computed (dynamic) value.

Parameters
Name Type Default Value Flags Description
factoryFn anonymous

The factory function creating the value. Both sync and async functions are supported.

toJSON() : Object

Convert to a plain JSON object

toProvider(providerClass: Constructor<Provider<T>>) : this

Bind the key to a value computed by a Provider.

  • @example
export class DateProvider implements Provider<Date> {
  constructor(@inject('stringDate') private param: String){}
  value(): Date {
    return new Date(param);
  }
}

Parameters
Name Type Default Value Flags Description
providerClass Constructor<Provider<T>>

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

unlock() : this

Unlock the binding

bind(key: BindingAddress<T>) : Binding<T>

A static method to create a binding so that we can do Binding.bind('foo').to('bar'); as new Binding('foo').to('bar') is not easy to read.

Parameters
Name Type Default Value Flags Description
key BindingAddress<T>

Binding key

configure(key: BindingAddress) : Binding<T>

Create a configuration binding for the given key

Parameters
Name Type Default Value Flags Description
key BindingAddress

Key for the binding to be configured

Type alias: BindingTemplate(binding: Binding<T>): void

A function as the template to configure bindings

Arguments
Name Type Description
binding Binding<T>

Type alias: TagMap = MapObject

Class: defaultconfigurationresolver = new DefaultConfigurationResolver()

Resolver for configurations of bindings

Properties
Name Type Default Value Flags Description
context Context public exported constructorProperty

Resolver for configurations of bindings

constructor(context: Context) : DefaultConfigurationResolver

Parameters
Name Type Default Value Flags Description
context Context

Resolver for configurations of bindings

getConfigAsValueOrPromise(key: BindingAddress<unknown>, configPath: undefined | string, resolutionOptions: ResolutionOptions) : ValueOrPromise<ConfigValueType | undefined>

Parameters
Name Type Default Value Flags Description
key BindingAddress<unknown>

Resolver for configurations of bindings

configPath undefined | string optional

Resolver for configurations of bindings

resolutionOptions ResolutionOptions optional

Resolver for configurations of bindings

Interface: ConfigurationResolver

Resolver for configuration of bindings. It's responsible for finding corresponding configuration for a given binding key.

By default, undefined is expected if no configuration is provided. The behavior can be overridden by setting optional to false in resolution options.

getConfigAsValueOrPromise(key: BindingAddress<unknown>, configPath: undefined | string, resolutionOptions: ResolutionOptions) : ValueOrPromise<ConfigValueType | undefined>

Resolve config for the binding key

Parameters
Name Type Default Value Flags Description
key BindingAddress<unknown>

Binding key

configPath undefined | string optional

Property path for the option. For example, x.y requests for <config>.x.y. If not set, the config object will be returned.

resolutionOptions ResolutionOptions optional

Options for the resolution.

  • optional: if not set or set to true, undefined will be returned if no corresponding value is found. Otherwise, an error will be thrown.

Function: configBindingKeyFor

configBindingKeyFor(key: BindingAddress, configPath: undefined | string) : BindingKey<ConfigValueType>

Create binding key for configuration of the binding

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key for the target binding

configPath undefined | string optional

Property path for the configuration

Namespace: bind

Function: bind.provider

bind.provider(specs: BindingSpec[]) : anonymous

@bind.provider to denote a provider class

A list of binding scope/tags or template functions to configure the binding

Parameters
Name Type Default Value Flags Description
specs BindingSpec[] rest

Type alias: BindingFilter(binding: Readonly<Binding<unknown>>): boolean

A function that filters bindings. It returns true to select a given binding.

Returns:

Arguments
Name Type Description
binding Readonly<Binding<unknown>>

Function: filterByKey

filterByKey(keyPattern: string | RegExp | BindingFilter) : BindingFilter

Create a binding filter from key pattern

Parameters
Name Type Default Value Flags Description
keyPattern string | RegExp | BindingFilter optional

Binding key/wildcard, regexp, or a filter function

Function: filterByTag

filterByTag(tagPattern: BindingTag | RegExp) : BindingFilter

Create a binding filter for the tag pattern

Parameters
Name Type Default Value Flags Description
tagPattern BindingTag | RegExp

Binding tag name, regexp, or object

Function: isBindingAddress

isBindingAddress(bindingSelector: BindingSelector) : boolean

Type guard for binding address

Parameters
Name Type Default Value Flags Description
bindingSelector BindingSelector

Type alias: TypeNamespaceMapping(name: string): string

Mapping artifact types to binding key namespaces (prefixes).

Returns:

Arguments
Name Type Description
name string

const BINDING_METADATA_KEY = MetadataAccessor.create< BindingMetadata, ClassDecorator >('binding.metadata')

Metadata key for binding metadata

Function: asBindingTemplate

asBindingTemplate(scopeAndTags: BindingScopeAndTags) : BindingTemplate

Convert binding scope and tags as a template function

Parameters
Name Type Default Value Flags Description
scopeAndTags BindingScopeAndTags

Binding scope and tags

Function: asClassOrProvider

asClassOrProvider(target: Constructor<unknown>) : BindingTemplate

A factory function to create a template function to bind the target class as a class or Provider.

Parameters
Name Type Default Value Flags Description
target Constructor<unknown>

Target class, which can be an implementation of Provider

Function: asProvider

asProvider(target: Constructor<Provider<unknown>>) : BindingTemplate

A factory function to create a template function to bind the target class as a Provider.

Parameters
Name Type Default Value Flags Description
target Constructor<Provider<unknown>>

Target provider class

Function: bindingTemplateFor

bindingTemplateFor(cls: Constructor<T | Provider<T>>) : BindingTemplate<T>

Get the binding template for a class with binding metadata

Parameters
Name Type Default Value Flags Description
cls Constructor<T | Provider<T>>

A class with optional @bind

Function: createBindingFromClass

createBindingFromClass(cls: Constructor<T | Provider<T>>, options: BindingFromClassOptions) : Binding<T>

Create a binding from a class with decorated metadata. The class is attached to the binding as follows:

  • binding.toClass(cls): if cls is a plain class such as MyController
  • binding.toProvider(cls): it cls is a value provider class with a prototype method value()

Parameters
Name Type Default Value Flags Description
cls Constructor<T | Provider<T>>

A class. It can be either a plain class or a value provider class

options BindingFromClassOptions {}

Options to customize the binding key

Function: getBindingMetadata

getBindingMetadata(target: Function) : BindingMetadata | undefined

Get binding metadata for a class

Parameters
Name Type Default Value Flags Description
target Function

The target class

Function: isProviderClass

isProviderClass(cls: Constructor<unknown>) : boolean

Check if a class implements Provider interface

Parameters
Name Type Default Value Flags Description
cls Constructor<unknown>

A class

Function: removeNameAndKeyTags

removeNameAndKeyTags(binding: Binding<unknown>) : void

A binding template function to delete name and key tags

Parameters
Name Type Default Value Flags Description
binding Binding<unknown>

Object literal: DEFAULT_TYPE_NAMESPACES

Variables
Name Type Default Value Flags Description
class string "classes" exported
provider string "providers" exported

Class: bindingkey = new BindingKey()

Properties
Name Type Default Value Flags Description
CONFIG_NAMESPACE string "$config" static exported

Name space for configuration binding keys

PROPERTY_SEPARATOR "#" static exported

deepProperty(propertyPath: string) : BindingKey<PropertyValueType>

Get a binding address for retrieving a deep property of the object bound to the current binding key.

Parameters
Name Type Default Value Flags Description
propertyPath string

A dot-separated path to a (deep) property, e.g. "server.port".

toString() : string

buildKeyForConfig(key: BindingAddress) : BindingAddress<T>

Build a binding key for the configuration of the given binding. The format is <key>:$config

Parameters
Name Type Default Value Flags Description
key BindingAddress ""

Key of the target binding to be configured

create(key: string, propertyPath: undefined | string) : BindingKey<ValueType>

Create a new key for a binding bound to a value of type ValueType.

Parameters
Name Type Default Value Flags Description
key string

The binding key. When propertyPath is not provided, the key is allowed to contain propertyPath as encoded via BindingKey#toString()

propertyPath undefined | string optional

Optional path to a deep property of the bound value.

parseKeyWithPath(keyWithPath: BindingAddress<T>) : BindingKey<T>

Parse a string containing both the binding key and the path to the deeply nested property to retrieve.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<T>

The key with an optional path, e.g. "application.instance" or "config#rest.port".

validate(key: BindingAddress<T>) : string

Validate the binding key format. Please note that # is reserved. Returns a string representation of the binding key.

Parameters
Name Type Default Value Flags Description
key BindingAddress<T>

Binding key, such as a, a.b, a:b, or a/b

Interface: BindingComparator

Compare function to sort an array of bindings. It is used by Array.prototype.sort().

Function: compareBindingsByTag

compareBindingsByTag(phaseTagName: string, orderOfPhases: (string | symbol)[]) : BindingComparator

Creates a binding compare function to sort bindings by tagged phase name.

Parameters
Name Type Default Value Flags Description
phaseTagName string "phase"

Name of the binding tag for phase

orderOfPhases (string | symbol)[] []

An array of phase names as the predefined order

Function: compareByOrder

compareByOrder(a: string | symbol | undefined | null, b: string | symbol | undefined | null, order: (string | symbol)[]) : number

Compare two values by the predefined order

Parameters
Name Type Default Value Flags Description
a string | symbol | undefined | null

First value

b string | symbol | undefined | null

Second value

order (string | symbol)[] []

An array of values as the predefined order

Function: sortBindingsByPhase

sortBindingsByPhase(bindings: Readonly<Binding<unknown>>[], phaseTagName: undefined | string, orderOfPhases: (string | symbol)[]) : anonymous[]

Sort bindings by phase names denoted by a tag and the predefined order

Parameters
Name Type Default Value Flags Description
bindings Readonly<Binding<unknown>>[]

An array of bindings

phaseTagName undefined | string optional

Tag name for phase, for example, we can use the value 'a' of tag order as the phase name for binding.tag({order: 'a'}).

orderOfPhases (string | symbol)[] optional

An array of phase names as the predefined order

Enumeration: BindingCreationPolicy

Policy to control if a binding should be created for the context

Members
Name Default Value Flags Description
ALWAYS_CREATE "Always" exported

Always create a binding with the key for the context

CREATE_IF_NOT_BOUND "IfNotBound" exported

Create a binding if the key is not bound in the context. Otherwise, return the existing binding.

NEVER_CREATE "Never" exported

Never create a binding for the context. If the key is not bound in the context, throw an error.

Class: context = new Context()

Context provides an implementation of Inversion of Control (IoC) container

Properties
Name Type Default Value Flags Description
name string exported

Name of the context

constructor(_parent: Context | string, name: undefined | string) : Context

Create a new context.

Parameters
Name Type Default Value Flags Description
_parent Context | string optional

The optional parent context

name undefined | string optional

Name of the context, if not provided, a uuid will be generated as the name

add(binding: Binding<unknown>) : this

Add a binding to the context. If a locked binding already exists with the same key, an error will be thrown.

Parameters
Name Type Default Value Flags Description
binding Binding<unknown>

The configured binding to be added

bind(key: BindingAddress<ValueType>) : Binding<ValueType>

Create a binding with the given key in the context. If a locked binding already exists with the same key, an error will be thrown.

Parameters
Name Type Default Value Flags Description
key BindingAddress<ValueType>

Binding key

close() : void

Close the context: clear observers, stop notifications, and remove event listeners from its parent context.

configure(key: BindingAddress) : Binding<ConfigValueType>

Create a corresponding binding for configuration of the target bound by the given key in the context.

For example, ctx.configure('controllers.MyController').to({x: 1}) will create binding controllers.MyController:$config with value {x: 1}.

Parameters
Name Type Default Value Flags Description
key BindingAddress ""

The key for the binding to be configured

contains(key: BindingAddress) : boolean

Check if a binding exists with the given key in the local context without delegating to the parent context

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

createView(filter: BindingFilter, comparator: BindingComparator) : ContextView<T>

Create a view of the context chain with the given binding filter

Parameters
Name Type Default Value Flags Description
filter BindingFilter

A function to match bindings

comparator BindingComparator optional

A function to sort matched bindings

find(pattern: string | RegExp | BindingFilter) : Readonly<Binding<ValueType>>[]

Find bindings using a key pattern or filter function

Parameters
Name Type Default Value Flags Description
pattern string | RegExp | BindingFilter optional

A filter function, a regexp or a wildcard pattern with optional * and ?. Find returns such bindings where the key matches the provided pattern.

For a wildcard:

  • * matches zero or more characters except . and :
  • ? matches exactly one character except . and :

For a filter function:

  • return true to include the binding in the results
  • return false to exclude it.

findByTag(tagFilter: BindingTag | RegExp) : Readonly<Binding<ValueType>>[]

Find bindings using the tag filter. If the filter matches one of the binding tags, the binding is included.

Parameters
Name Type Default Value Flags Description
tagFilter BindingTag | RegExp

A filter for tags. It can be in one of the following forms:

  • A regular expression, such as /controller/
  • A wildcard pattern string with optional * and ?, such as 'con*' For a wildcard:
    • * matches zero or more characters except . and :
    • ? matches exactly one character except . and :
  • An object containing tag name/value pairs, such as {name: 'my-controller'}

findOrCreateBinding(key: BindingAddress<T>, policy: BindingCreationPolicy) : Binding<T>

Find or create a binding for the given key

Parameters
Name Type Default Value Flags Description
key BindingAddress<T>

Binding address

policy BindingCreationPolicy optional

Binding creation policy

get(keyWithPath: BindingAddress<ValueType>, session: ResolutionSession) : Promise<ValueType>

Get the value bound to the given key, throw an error when no value is bound for the given key.

Returns:

A promise of the bound value.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

session ResolutionSession optional

Optional session for resolution (accepted for backward compatibility)

get(keyWithPath: BindingAddress<ValueType>, options: ResolutionOptions) : Promise<ValueType | undefined>

Get the value bound to the given key, optionally return a (deep) property of the bound value.

Returns:

A promise of the bound value, or a promise of undefined when the optional binding is not found.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

options ResolutionOptions

Options for resolution.

getBinding(key: BindingAddress<ValueType>) : Binding<ValueType>

Look up a binding by key in the context and its ancestors. If no matching binding is found, an error will be thrown.

Parameters
Name Type Default Value Flags Description
key BindingAddress<ValueType>

Binding key

getBinding(key: BindingAddress<ValueType>, options: undefined | anonymous) : Binding<ValueType> | undefined

Look up a binding by key in the context and its ancestors. If no matching binding is found and options.optional is not set to true, an error will be thrown.

Parameters
Name Type Default Value Flags Description
key BindingAddress<ValueType>

Binding key

options undefined | anonymous optional

Options to control if the binding is optional. If `options.optional` is set to true, the method will return `undefined` instead of throwing an error if the binding key is not found.

getConfig(key: BindingAddress, configPath: undefined | string, resolutionOptions: ResolutionOptions) : Promise<ConfigValueType | undefined>

Resolve configuration for the binding by key

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

configPath undefined | string optional

Property path for the option. For example, x.y requests for <config>.x.y. If not set, the <config> object will be returned.

resolutionOptions ResolutionOptions optional

Options for the resolution.

getConfigAsValueOrPromise(key: BindingAddress, configPath: undefined | string, resolutionOptions: ResolutionOptions) : ValueOrPromise<ConfigValueType | undefined>

Get the value or promise of configuration for a given binding by key

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

configPath undefined | string optional

Property path for the option. For example, x.y requests for <config>.x.y. If not set, the <config> object will be returned.

resolutionOptions ResolutionOptions optional

Options for the resolution.

  • optional: if not set or set to true, undefined will be returned if no corresponding value is found. Otherwise, an error will be thrown.

getConfigSync(key: BindingAddress, configPath: undefined | string, resolutionOptions: ResolutionOptions) : ConfigValueType | undefined

Resolve configuration synchronously for the binding by key

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

configPath undefined | string optional

Property path for the option. For example, x.y requests for config.x.y. If not set, the config object will be returned.

resolutionOptions ResolutionOptions optional

Options for the resolution.

getOwnerContext(key: BindingAddress) : Context | undefined

Get the owning context for a binding key

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

getSync(keyWithPath: BindingAddress<ValueType>, session: ResolutionSession) : ValueType

Get the synchronous value bound to the given key, optionally return a (deep) property of the bound value.

This method throws an error if the bound value requires async computation (returns a promise). You should never rely on sync bindings in production code.

Returns:

A promise of the bound value.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

session ResolutionSession optional

Session for resolution (accepted for backward compatibility)

getSync(keyWithPath: BindingAddress<ValueType>, options: ResolutionOptions) : ValueType | undefined

Get the synchronous value bound to the given key, optionally return a (deep) property of the bound value.

This method throws an error if the bound value requires async computation (returns a promise). You should never rely on sync bindings in production code.

Returns:

The bound value, or undefined when an optional binding is not found.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

options ResolutionOptions optional

Options for resolution.

getValueOrPromise(keyWithPath: BindingAddress<ValueType>, optionsOrSession: ResolutionOptionsOrSession) : ValueOrPromise<ValueType | undefined>

Get the value bound to the given key.

This is an internal version that preserves the dual sync/async result of Binding#getValue(). Users should use get() or getSync() instead.

Returns:

The bound value or a promise of the bound value, depending on how the binding is configured.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

optionsOrSession ResolutionOptionsOrSession optional

Options for resolution or a session

isBound(key: BindingAddress) : boolean

Check if a key is bound in the context or its ancestors

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

isSubscribed(observer: ContextObserver) : boolean

Check if an observer is subscribed to this context

Parameters
Name Type Default Value Flags Description
observer ContextObserver

Context observer

subscribe(observer: ContextEventObserver) : Subscription

Add a context event observer to the context

Parameters
Name Type Default Value Flags Description
observer ContextEventObserver

Context observer instance or function

toJSON() : Object

Create a plain JSON object for the context

unbind(key: BindingAddress) : boolean

Unbind a binding from the context. No parent contexts will be checked.

Returns:

true if the binding key is found and removed from this context

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

unsubscribe(observer: ContextEventObserver) : boolean

Remove the context event observer from the context

Parameters
Name Type Default Value Flags Description
observer ContextEventObserver

Context event observer

Interface: ContextObserver

Observers of context bind/unbind events

Properties
Name Type Default Value Flags Description
filter BindingFilter exported optional

An optional filter function to match bindings. If not present, the listener will be notified of all binding events.

observe ContextObserverFn exported

Listen on bind, unbind, or other events

Interface: Subscription

Subscription of context events. It's modeled after https://github.com/tc39/proposal-observable.

Properties
Name Type Default Value Flags Description
closed boolean exported

Is the subscription closed?

unsubscribe() : void

unsubscribe

Type alias: ContextObserverFn(eventType: ContextEventType, binding: Readonly<Binding<unknown>>, context: Context): ValueOrPromise

Listen on bind, unbind, or other events

Returns:

Arguments
Name Type Description
eventType ContextEventType

Context event type

binding Readonly<Binding<unknown>>

The binding as event source

context Context

Context object for the binding event

Class: contextview = new ContextView()

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

Properties
Name Type Default Value Flags Description
comparator BindingComparator public exported optional constructorProperty

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

filter BindingFilter public exported constructorProperty

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

constructor(context: Context, filter: BindingFilter, comparator: BindingComparator) : ContextView

Parameters
Name Type Default Value Flags Description
context Context

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

filter BindingFilter

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

comparator BindingComparator optional

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

bindings() :

asGetter(session: ResolutionSession) : Getter<T[]>

As a Getter function

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

close() : void

Stop listening events from the context

observe(event: ContextEventType, binding: Readonly<Binding<unknown>>) : void

Listen on bind or unbind and invalidate the cache

Parameters
Name Type Default Value Flags Description
event ContextEventType

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

binding Readonly<Binding<unknown>>

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

open() : undefined | Subscription

Start listening events from the context

refresh() : void

Refresh the view by invalidating its cache

resolve(session: ResolutionSession) : ValueOrPromise<T[]>

Resolve values for the matching bindings

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

Resolution session

singleValue(session: ResolutionSession) : Promise<T | undefined>

Get the single value

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

values(session: ResolutionSession) : Promise<T[]>

Get the list of resolved values. If they are not cached, it tries to find and resolve them.

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

Function: createViewGetter

createViewGetter(ctx: Context, bindingFilter: BindingFilter, session: ResolutionSession) : Getter<T[]>

Create a context view as a getter with the given filter

Parameters
Name Type Default Value Flags Description
ctx Context

Context object

bindingFilter BindingFilter

A function to match bindings

session ResolutionSession optional

Resolution session if the comparator is provided

createViewGetter(ctx: Context, bindingFilter: BindingFilter, bindingComparator: BindingComparator, session: ResolutionSession) : Getter<T[]>

Create a context view as a getter with the given filter and sort matched bindings by the comparator.

Parameters
Name Type Default Value Flags Description
ctx Context

Context object

bindingFilter BindingFilter

A function to match bindings

bindingComparator BindingComparator optional

A function to compare two bindings

session ResolutionSession optional

Resolution session if the comparator is provided

Namespace: Getter

The function injected by @inject.getter(bindingSelector). It can be used to fetch bound value(s) from the underlying binding(s). The return value will be an array if the bindingSelector is a BindingFilter function.

Function: Getter.fromValue

Getter.fromValue(value: T) : Getter<T>

Convert a value into a Getter returning that value.

Parameters
Name Type Default Value Flags Description
value T

Namespace: inject

Function: inject.binding

inject.binding(bindingKey: BindingAddress, metadata: InjectBindingMetadata) : markParameterOrPropertyAsInjected

Inject the binding object for the given key. This is useful if a binding needs to be set up beyond just a constant value allowed by @inject.setter. The injected binding is found or created based on the metadata.bindingCreation option. See BindingCreationPolicy for more details.

Parameters
Name Type Default Value Flags Description
bindingKey BindingAddress

Binding key

metadata InjectBindingMetadata optional

Metadata for the injection

Function: inject.context

inject.context() : markParameterOrPropertyAsInjected

Inject the context object.

Function: inject.getter

inject.getter(bindingSelector: BindingSelector<unknown>, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject a function for getting the actual bound value.

This is useful when implementing Actions, where the action is instantiated for Sequence constructor, but some of action's dependencies become bound only after other actions have been executed by the sequence.

See also Getter<T>.

Parameters
Name Type Default Value Flags Description
bindingSelector BindingSelector<unknown>

The binding key or filter we want to eventually get value(s) from.

metadata InjectionMetadata optional

Optional metadata to help the injection

Function: inject.setter

inject.setter(bindingKey: BindingAddress, metadata: InjectBindingMetadata) : markParameterOrPropertyAsInjected

Inject a function for setting (binding) the given key to a given value. (Only static/constant values are supported, it's not possible to bind a key to a class or a provider.)

This is useful e.g. when implementing Actions that are contributing new Elements.

See also Setter<T>.

Parameters
Name Type Default Value Flags Description
bindingKey BindingAddress

The key of the value we want to set.

metadata InjectBindingMetadata optional

Optional metadata to help the injection

Function: inject.tag

inject.tag(bindingTag: BindingTag | RegExp, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject an array of values by a tag pattern string or regexp

Parameters
Name Type Default Value Flags Description
bindingTag BindingTag | RegExp

Tag name, regex or object

metadata InjectionMetadata optional

Optional metadata to help the injection

Function: inject.view

inject.view(bindingFilter: BindingFilter, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject matching bound values by the filter function

Parameters
Name Type Default Value Flags Description
bindingFilter BindingFilter

A binding filter function

metadata InjectionMetadata optional

Interface: InjectBindingMetadata

Metadata for @inject.binding

Properties
Name Type Default Value Flags Description
bindingCreation BindingCreationPolicy exported optional

Controls how the underlying binding is resolved/created

Interface: Injection

Descriptor for an injection point

Properties
Name Type Default Value Flags Description
bindingSelector BindingSelector<ValueType> exported

Descriptor for an injection point

member undefined | string exported optional

Descriptor for an injection point

metadata InjectionMetadata exported

Descriptor for an injection point

methodDescriptorOrParameterIndex TypedPropertyDescriptor<ValueType> | number exported optional

Descriptor for an injection point

resolve ResolverFunction exported optional

Descriptor for an injection point

target Object exported

Descriptor for an injection point

Interface: InjectionMetadata

An object to provide metadata for @inject

Properties
Name Type Default Value Flags Description
bindingComparator BindingComparator exported optional

Optional comparator for matched bindings

decorator undefined | string exported optional

Name of the decorator function, such as @inject or @inject.setter. It's usually set by the decorator implementation.

Interface: ResolverFunction

A function to provide resolution of injected values

Type alias: Setter(value: T): void

The function injected by @inject.setter(bindingKey). It sets the underlying binding to a constant value using binding.to(value).

Returns:

Arguments
Name Type Description
value T

The value for the underlying binding

Function: assertTargetType

assertTargetType(injection: Readonly<Injection>, expectedType: Function, expectedTypeName: undefined | string) : undefined | string

Assert the target type inspected from TypeScript for injection to be the expected type. If the types don't match, an error is thrown.

Returns:

The name of the target

Parameters
Name Type Default Value Flags Description
injection Readonly<Injection>

Injection information

expectedType Function

Expected type

expectedTypeName undefined | string optional

Name of the expected type to be used in the error

Function: describeInjectedArguments

describeInjectedArguments(target: Object, method: undefined | string) : Readonly<Injection>[]

Return an array of injection objects for parameters

Parameters
Name Type Default Value Flags Description
target Object

The target class for constructor or static methods, or the prototype for instance methods

method undefined | string optional

Method name, undefined for constructor

Function: describeInjectedProperties

describeInjectedProperties(target: Object) : MetadataMap<Readonly<Injection>>

Return a map of injection objects for properties

Parameters
Name Type Default Value Flags Description
target Object

The target class for static properties or prototype for instance properties.

Function: inspectTargetType

inspectTargetType(injection: Readonly<Injection>) : Function

Inspect the target type for the injection to find out the corresponding JavaScript type

Parameters
Name Type Default Value Flags Description
injection Readonly<Injection>

Injection information

Namespace: config

Function: config.getter

config.getter(configPath: undefined | string, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

@inject.getter decorator to inject a config getter function

Parameters
Name Type Default Value Flags Description
configPath undefined | string optional

Optional property path of the config object

metadata InjectionMetadata optional

Injection metadata

Function: config.view

config.view(configPath: undefined | string, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

@inject.view decorator to inject a config context view to allow dynamic changes in configuration

Parameters
Name Type Default Value Flags Description
configPath undefined | string optional

Optional property path of the config object

metadata InjectionMetadata optional

Injection metadata

Class: interceptionhandler = new InterceptionHandler()

constructor(context: Context) : InterceptionHandler

Parameters
Name Type Default Value Flags Description
context Context new Context()

get(target: T, propertyName: PropertyKey, receiver: unknown) : any

Parameters
Name Type Default Value Flags Description
target T
propertyName PropertyKey
receiver unknown

Function: createProxyWithInterceptors

createProxyWithInterceptors(target: T, context: Context) : AsyncProxy<T>

Create a proxy that applies interceptors for method invocations

Parameters
Name Type Default Value Flags Description
target T

Target class or object

context Context optional

Context object

Class: invocationcontext = new InvocationContext()

InvocationContext represents the context to invoke interceptors for a method. The context can be used to access metadata about the invocation as well as other dependencies.

Properties
Name Type Default Value Flags Description
args InvocationArgs public exported constructorProperty

An array of arguments

methodName string public exported constructorProperty

Method name

target object public exported constructorProperty

Target class (for static methods) or prototype/object (for instance methods)

constructor(parent: Context, target: object, methodName: string, args: InvocationArgs) : InvocationContext

Construct a new instance of InvocationContext

Parameters
Name Type Default Value Flags Description
parent Context

Parent context, such as the RequestContext

target object

Target class (for static methods) or prototype/object (for instance methods)

methodName string

Method name

args InvocationArgs

An array of arguments

description() :

targetClass() :

targetName() :

assertMethodExists() : anonymous

Assert the method exists on the target. An error will be thrown if otherwise.

getGlobalInterceptorBindingKeys() : string[]

Discover all binding keys for global interceptors (tagged by ContextTags.GLOBAL_INTERCEPTOR)

invokeTargetMethod() : any

Invoke the target method with the given context

loadInterceptors() : (string | Interceptor | BindingKey<Interceptor>)[]

Load all interceptors for the given invocation context. It adds interceptors from possibly three sources:

  1. method level @intercept
  2. class level @intercept
  3. global interceptors discovered in the context

toString() : string

Interface: Interceptor

Interceptor function to intercept method invocations

Type alias: InvocationArgs = any[]

Type alias: InvocationResult = any

const INTERCEPT_CLASS_KEY = MetadataAccessor.create< InterceptorOrKey[], ClassDecorator >('intercept:class')

Metadata key for method-level interceptors

const INTERCEPT_METHOD_KEY = MetadataAccessor.create< InterceptorOrKey[], MethodDecorator >('intercept:method')

Metadata key for method-level interceptors

Function: asGlobalInterceptor

asGlobalInterceptor(group: undefined | string) : BindingTemplate

The BindingTemplate function to configure a binding as a global interceptor by tagging it with ContextTags.INTERCEPTOR

Parameters
Name Type Default Value Flags Description
group undefined | string optional

Function: intercept

intercept(interceptorOrKeys: InterceptorOrKey[]) : interceptDecoratorForClassOrMethod

Decorator function @intercept for classes/methods to apply interceptors. It can be applied on a class and its public methods. Multiple occurrences of @intercept are allowed on the same target class or method. The decorator takes a list of interceptor functions or binding keys.

Parameters
Name Type Default Value Flags Description
interceptorOrKeys InterceptorOrKey[] rest

One or more interceptors or binding keys that are resolved to be interceptors

Function: invokeMethodWithInterceptors

invokeMethodWithInterceptors(context: Context, target: object, methodName: string, args: InvocationArgs) : ValueOrPromise<InvocationResult>

Invoke a method with the given context

Parameters
Name Type Default Value Flags Description
context Context

Context object

target object

Target class (for static methods) or object (for instance methods)

methodName string

Method name

args InvocationArgs

An array of argument values

Function: mergeInterceptors

mergeInterceptors(interceptorsFromSpec: InterceptorOrKey[], existingInterceptors: InterceptorOrKey[]) : (string | Interceptor | BindingKey<Interceptor>)[]

Adding interceptors from the spec to the front of existing ones. Duplicate entries are eliminated from the spec side.

For example:

  • [log] + [cache, log] => [cache, log]
  • [log] + [log, cache] => [log, cache]
  • [] + [cache, log] => [cache, log]
  • [cache, log] + [] => [cache, log]
  • [log] + [cache] => [log, cache]

Parameters
Name Type Default Value Flags Description
interceptorsFromSpec InterceptorOrKey[]

Interceptors from @intercept

existingInterceptors InterceptorOrKey[]

Interceptors already applied for the method

Namespace: ContextBindings

Namespace for context bindings

const ContextBindings.CONFIGURATION_RESOLVER = BindingKey.create< ConfigurationResolver >(`${BindingKey.CONFIG_NAMESPACE}.resolver`)

Binding key for ConfigurationResolver

const ContextBindings.GLOBAL_INTERCEPTOR_ORDERED_GROUPS = BindingKey.create( 'globalInterceptor.orderedGroups', )

Binding key for ordered groups of global interceptors

Namespace: ContextTags

Namespace for context tags

const ContextTags.CLASS = "class"

Namespace for context tags

const ContextTags.CONFIGURATION_FOR = "configurationFor"

Binding tag to associate a configuration binding with the target binding key

const ContextTags.GLOBAL_INTERCEPTOR = "globalInterceptor"

Binding tag for global interceptors

const ContextTags.GLOBAL_INTERCEPTOR_GROUP = "globalInterceptorGroup"

Binding tag for group name of global interceptors

const ContextTags.KEY = "key"

Binding key for the artifact

const ContextTags.NAME = "name"

Name of the artifact

const ContextTags.NAMESPACE = "namespace"

Namespace of the artifact

const ContextTags.PROVIDER = "provider"

Namespace for context tags

const ContextTags.TYPE = "type"

Type of the artifact

Interface: Provider

Providers allow developers to compute injected values dynamically, with any dependencies required by the value getter injected automatically from the Context.

value() : ValueOrPromise<T>

Returns:

The value to inject to dependents. This method can return a promise too, in which case the IoC framework will resolve this promise to obtain the value to inject.

Class: resolutionsession = new ResolutionSession()

Object to keep states for a session to resolve bindings and their dependencies within a context

Properties
Name Type Default Value Flags Description
stack ResolutionElement[] [] exported

A stack of bindings for the current resolution session. It's used to track the path of dependency resolution and detect circular dependencies.

bindingStack() :

currentBinding() :

currentInjection() :

injectionStack() :

getBindingPath() : string

Get the binding path as bindingA --> bindingB --> bindingC.

getInjectionPath() : string

Get the injection path as injectionA --> injectionB --> injectionC.

getResolutionPath() : string

Get the resolution path including bindings and injections, for example: bindingA --> @ClassA[0] --> bindingB --> @ClassB.prototype.prop1 --> bindingC.

popBinding() : Readonly<Binding>

Exit the resolution of a binding

popInjection() : anonymous

Pop the last injection

pushBinding(binding: Readonly<Binding>) : void

Enter the resolution of the given binding. If

Parameters
Name Type Default Value Flags Description
binding Readonly<Binding>

Binding

pushInjection(injection: Readonly<Injection>) : void

Push the injection onto the session

Parameters
Name Type Default Value Flags Description
injection Readonly<Injection>

Injection The current injection

describeInjection(injection: Readonly<Injection>) : anonymous | anonymous

Describe the injection for debugging purpose

Parameters
Name Type Default Value Flags Description
injection Readonly<Injection> optional

Injection object

fork(session: ResolutionSession) : ResolutionSession | undefined

Fork the current session so that a new one with the same stack can be used in parallel or future resolutions, such as multiple method arguments, multiple properties, or a getter function

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

The current session

runWithBinding(action: ResolutionAction, binding: Readonly<Binding>, session: ResolutionSession) : any

Run the given action with the given binding and session

Parameters
Name Type Default Value Flags Description
action ResolutionAction

A function to do some work with the resolution session

binding Readonly<Binding>

The current binding

session ResolutionSession optional

The current resolution session

runWithInjection(action: ResolutionAction, injection: Readonly<Injection>, session: ResolutionSession) : any

Run the given action with the given injection and session

Parameters
Name Type Default Value Flags Description
action ResolutionAction

A function to do some work with the resolution session

injection Readonly<Injection>

Object to keep states for a session to resolve bindings and their dependencies within a context

session ResolutionSession optional

The current resolution session

Interface: BindingElement

Wrapper for bindings tracked by resolution sessions

Properties
Name Type Default Value Flags Description
type exported

Wrapper for bindings tracked by resolution sessions

value Readonly<Binding> exported

Wrapper for bindings tracked by resolution sessions

Interface: InjectionElement

Wrapper for injections tracked by resolution sessions

Properties
Name Type Default Value Flags Description
type exported

Wrapper for injections tracked by resolution sessions

value Readonly<Injection> exported

Wrapper for injections tracked by resolution sessions

Interface: ResolutionOptions

Options for binding/dependency resolution

Properties
Name Type Default Value Flags Description
asProxyWithInterceptors undefined | false | true exported optional

A boolean flag to control if a proxy should be created to apply interceptors for the resolved value. It's only honored for bindings backed by a class.

optional undefined | false | true exported optional

A boolean flag to indicate if the dependency is optional. If it's set to true and the binding is not bound in a context, the resolution will return undefined instead of throwing an error.

session ResolutionSession exported optional

A session to track bindings and injections

Type alias: ResolutionAction(session: ResolutionSession): ValueOrPromise

A function to be executed with the resolution session

Arguments
Name Type Description
session ResolutionSession

Function: asResolutionOptions

asResolutionOptions(optionsOrSession: ResolutionOptionsOrSession) : ResolutionOptions

Normalize ResolutionOptionsOrSession to ResolutionOptions

Parameters
Name Type Default Value Flags Description
optionsOrSession ResolutionOptionsOrSession optional

resolution options or session

Function: instantiateClass

instantiateClass(ctor: Constructor<T>, ctx: Context, session: ResolutionSession, nonInjectedArgs: any[]) : ValueOrPromise<T>

Create an instance of a class which constructor has arguments decorated with @inject.

The function returns a class when all dependencies were resolved synchronously, or a Promise otherwise.

Parameters
Name Type Default Value Flags Description
ctor Constructor<T>

The class constructor to call.

ctx Context

The context containing values for @inject resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

nonInjectedArgs any[] optional

Optional array of args for non-injected parameters

Function: invokeMethod

invokeMethod(target: Object, method: string, ctx: Context, nonInjectedArgs: any[]) : ValueOrPromise<BoundValue>

Invoke an instance method with dependency injection

Parameters
Name Type Default Value Flags Description
target Object

Target of the method, it will be the class for a static method, and instance or class prototype for a prototype method

method string

Name of the method

ctx Context

Context

nonInjectedArgs any[] optional

Optional array of args for non-injected parameters

Function: resolveInjectedArguments

resolveInjectedArguments(target: Object, method: string, ctx: Context, session: ResolutionSession, nonInjectedArgs: any[]) : ValueOrPromise<BoundValue[]>

Given a function with arguments decorated with @inject, return the list of arguments resolved using the values bound in ctx.

The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.

Parameters
Name Type Default Value Flags Description
target Object

The class for constructor injection or prototype for method injection

method string

The method name. If set to '', the constructor will be used.

ctx Context

The context containing values for @inject resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

nonInjectedArgs any[] optional

Optional array of args for non-injected parameters

Function: resolveInjectedProperties

resolveInjectedProperties(constructor: Function, ctx: Context, session: ResolutionSession) : ValueOrPromise<MapObject<BoundValue>>

Given a class with properties decorated with @inject, return the map of properties resolved using the values bound in ctx.

The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.

Parameters
Name Type Default Value Flags Description
constructor Function

The class for which properties should be resolved.

ctx Context

The context containing values for @inject resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

Type alias: BoundValue = any

Type alias: MapObject(name: string): T

Arguments
Name Type Description
name string

Function: getDeepProperty

getDeepProperty(value: IN, path: string) : OUT | undefined

Get nested properties of an object by path

Parameters
Name Type Default Value Flags Description
value IN

Value of the source object

path string

Path to the property

Function: isPromiseLike

isPromiseLike(value: T | PromiseLike<T> | undefined) : boolean

Check whether a value is a Promise-like instance. Recognizes both native promises and third-party promise libraries.

Parameters
Name Type Default Value Flags Description
value T | PromiseLike<T> | undefined

The value to check.

Function: resolveList

resolveList(list: T[], resolver: (val: T, index: number, list: T[]) => ValueOrPromise<V>) : ValueOrPromise<V[]>

Resolve entries of an array into a new array with the same indexes. If one or more entries of the source array are resolved to a promise by the resolver function, this method returns a promise which will be resolved to the new array with fully resolved entries.

Parameters
Name Type Default Value Flags Description
list T[]

The original array containing the source entries

resolver anonymous

A function resolves an entry to a value or promise. It will be invoked with the property value, the property index, and the source array.

Function: resolveMap

resolveMap(map: MapObject<T>, resolver: (val: T, key: string, map: MapObject<T>) => ValueOrPromise<V>) : ValueOrPromise<MapObject<V>>

Resolve entries of an object into a new object with the same keys. If one or more entries of the source object are resolved to a promise by the resolver function, this method returns a promise which will be resolved to the new object with fully resolved entries.

Parameters
Name Type Default Value Flags Description
map MapObject<T>

The original object containing the source entries

resolver anonymous

A function resolves an entry to a value or promise. It will be invoked with the property value, the property name, and the source object.

Function: resolveUntil

resolveUntil(source: Iterator<T>, resolver: (sourceVal: T) => ValueOrPromise<V | undefined>, evaluator: (sourceVal: T, targetVal: V | undefined) => boolean) : ValueOrPromise<V | undefined>

Resolve an iterator of source values into a result until the evaluator returns true

Parameters
Name Type Default Value Flags Description
source Iterator<T>

The iterator of source values

resolver anonymous

The resolve function that maps the source value to a result

evaluator anonymous

The evaluate function that decides when to stop

Function: transformValueOrPromise

transformValueOrPromise(valueOrPromise: ValueOrPromise<T>, transformer: (val: T) => ValueOrPromise<V>) : ValueOrPromise<V>

Transform a value or promise with a function that produces a new value or promise

Parameters
Name Type Default Value Flags Description
valueOrPromise ValueOrPromise<T>

The value or promise

transformer anonymous

A function that maps the source value to a value or promise

Function: tryWithFinally

tryWithFinally(action: () => ValueOrPromise<T>, finalAction: () => void) : ValueOrPromise<T>

Try to run an action that returns a promise or a value

Parameters
Name Type Default Value Flags Description
action anonymous

A function that returns a promise or a value

finalAction anonymous

A function to be called once the action is fulfilled or rejected (synchronously or asynchronously)