@loopback/context
- Version 7.0.9
- Published
- 663 kB
- 7 dependencies
- MIT license
Install
npm i @loopback/context
yarn add @loopback/context
pnpm add @loopback/context
Overview
Facilities to manage artifacts and their dependencies in your Node.js applications. The module exposes TypeScript/JavaScript APIs and decorators to register artifacts, declare dependencies, and resolve artifacts by keys. It also serves as an IoC container
Index
Variables
Functions
- asBindingTemplate()
- asClassOrProvider()
- asGlobalInterceptor()
- asProvider()
- asResolutionOptions()
- assertTargetType()
- bind()
- bindingTemplateFor()
- compareBindingsByTag()
- compareByOrder()
- composeInterceptors()
- config()
- configBindingKeyFor()
- createBindingFromClass()
- createProxyWithInterceptors()
- createViewGetter()
- describeInjectedArguments()
- describeInjectedProperties()
- filterByKey()
- filterByTag()
- getBindingMetadata()
- getDeepProperty()
- globalInterceptor()
- hasInjections()
- includesTagValue()
- inject()
- injectable()
- inspectInjections()
- inspectTargetType()
- instantiateClass()
- intercept()
- invokeInterceptors()
- invokeMethod()
- invokeMethodWithInterceptors()
- isBindingAddress()
- isBindingTagFilter()
- isDynamicValueProviderClass()
- isPromiseLike()
- isProviderClass()
- mergeInterceptors()
- registerInterceptor()
- removeNameAndKeyTags()
- resolveInjectedArguments()
- resolveInjectedProperties()
- resolveList()
- resolveMap()
- resolveUntil()
- sortBindingsByPhase()
- transformValueOrPromise()
- tryCatchFinally()
- tryWithFinally()
- uuid()
Classes
Context
- add()
- bind()
- close()
- configResolver
- configure()
- contains()
- createView()
- debug()
- emitError()
- emitEvent()
- find()
- findByTag()
- findOrCreateBinding()
- get()
- getBinding()
- getConfig()
- getConfigAsValueOrPromise()
- getConfigSync()
- getDebugNamespace()
- getOwnerContext()
- getResolutionContext()
- getScopedContext()
- getSync()
- inspect()
- isBound()
- isSubscribed()
- isVisibleTo()
- name
- on()
- once()
- registry
- scope
- setupConfigurationResolverIfNeeded()
- subscribe()
- subscriptionManager
- tagIndexer
- toJSON()
- unbind()
- unsubscribe()
Interfaces
Enums
Type Aliases
- AliasBindingSource
- AsInterceptedFunction
- AsValueOrPromise
- AsyncProxy
- BindingAddress
- BindingEvent
- BindingEventListener
- BindingFromClassOptions
- BindingMetadata
- BindingScopeAndTags
- BindingSelector
- BindingSource
- BindingSpec
- BindingTag
- BindingTemplate
- BoundValue
- ClassBindingSource
- ConstantBindingSource
- Constructor
- ContextEvent
- ContextEventListener
- ContextEventObserver
- ContextEventType
- ContextObserverFn
- DynamicValueBindingSource
- GenericInterceptor
- GenericInterceptorOrKey
- Getter
- InterceptorOrKey
- InvocationArgs
- InvocationOptions
- InvocationResult
- JSONPrimitive
- JSONValue
- MapObject
- Next
- NonVoid
- ProviderBindingSource
- ResolutionAction
- ResolutionElement
- ResolutionOptionsOrSession
- Setter
- TagMap
- TypeNamespaceMapping
- ValueFactory
- ValueOrPromise
Namespaces
Variables
variable ANY_TAG_VALUE
const ANY_TAG_VALUE: TagValueMatcher;
A symbol that can be used to match binding tags by name regardless of the value.
Example 1
The following code matches bindings with tag
{controller: 'A'}
or{controller: 'controller'}
. But if the tag name 'controller' does not exist for a binding, the binding will NOT be included.ctx.findByTag({controller: ANY_TAG_VALUE})
variable BINDING_METADATA_KEY
const BINDING_METADATA_KEY: MetadataAccessor< BindingMetadata<unknown>, ClassDecorator>;
Metadata key for binding metadata
variable DEFAULT_TYPE_NAMESPACES
const DEFAULT_TYPE_NAMESPACES: TypeNamespaceMapping;
variable GLOBAL_INTERCEPTOR_NAMESPACE
const GLOBAL_INTERCEPTOR_NAMESPACE: string;
Default namespace for global interceptors
variable INTERCEPT_CLASS_KEY
const INTERCEPT_CLASS_KEY: MetadataAccessor<InterceptorOrKey[], ClassDecorator>;
Metadata key for method-level interceptors
variable INTERCEPT_METHOD_KEY
const INTERCEPT_METHOD_KEY: MetadataAccessor<InterceptorOrKey[], MethodDecorator>;
Metadata key for method-level interceptors
variable LOCAL_INTERCEPTOR_NAMESPACE
const LOCAL_INTERCEPTOR_NAMESPACE: string;
Default namespace for local interceptors
variable UUID_PATTERN
const UUID_PATTERN: RegExp;
A regular expression for testing uuid v4 PATTERN
Deprecated
This pattern is an internal helper used by unit-tests, we are no longer using it.
Functions
function asBindingTemplate
asBindingTemplate: <T = unknown>( scopeAndTags: BindingScopeAndTags) => BindingTemplate<T>;
Convert binding scope and tags as a template function
Parameter scopeAndTags
Binding scope and tags
function asClassOrProvider
asClassOrProvider: <T>( target: Constructor<T | Provider<T>> | DynamicValueProviderClass<T>) => BindingTemplate<T>;
A factory function to create a template function to bind the target class as a class or
Provider
.Parameter target
Target class, which can be an implementation of
Provider
orDynamicValueProviderClass
function asGlobalInterceptor
asGlobalInterceptor: (group?: string) => BindingTemplate;
The
BindingTemplate
function to configure a binding as a global interceptor by tagging it withContextTags.INTERCEPTOR
Parameter group
Group for ordering the interceptor
function asProvider
asProvider: <T>(target: Constructor<Provider<T>>) => BindingTemplate<T>;
A factory function to create a template function to bind the target class as a
Provider
.Parameter target
Target provider class
function asResolutionOptions
asResolutionOptions: ( optionsOrSession?: ResolutionOptionsOrSession) => ResolutionOptions;
Normalize ResolutionOptionsOrSession to ResolutionOptions
Parameter optionsOrSession
resolution options or session
function assertTargetType
assertTargetType: ( injection: Readonly<Injection>, expectedType: Function, expectedTypeName?: string) => 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.
Parameter injection
Injection information
Parameter expectedType
Expected type
Parameter expectedTypeName
Name of the expected type to be used in the error
Returns
The name of the target
function bind
bind: typeof bind;
See documentation for injectable.
function bindingTemplateFor
bindingTemplateFor: <T>( cls: Constructor<T | Provider<T>> | DynamicValueProviderClass<T>, options?: BindingFromClassOptions) => BindingTemplate<T>;
Get the binding template for a class with binding metadata
Parameter cls
A class with optional
@injectable
function compareBindingsByTag
compareBindingsByTag: ( phaseTagName?: string, orderOfPhases?: (string | symbol)[]) => BindingComparator;
Creates a binding compare function to sort bindings by tagged phase name.
Parameter phaseTagName
Name of the binding tag for phase
Parameter orderOfPhases
An array of phase names as the predefined order
Remarks
Two bindings are compared as follows:
1. Get values for the given tag as
phase
for bindings, if the tag is not present, defaultphase
to''
. 2. If both bindings havephase
value inorderOfPhases
, honor the order specified byorderOfPhases
. 3. If a binding'sphase
does not exist inorderOfPhases
, it comes before the one withphase
exists inorderOfPhases
. 4. If both bindings havephase
value outside oforderOfPhases
, they are ordered by phase names alphabetically and symbol values come before string values.
function compareByOrder
compareByOrder: ( a: string | symbol | undefined | null, b: string | symbol | undefined | null, order?: (string | symbol)[]) => number;
Compare two values by the predefined order
Parameter a
First value
Parameter b
Second value
Parameter order
An array of values as the predefined order
Remarks
The comparison is performed as follows:
1. If both values are included in
order
, they are sorted by their indexes inorder
. 2. The value included inorder
comes after the value not included inorder
. 3. If neither values are included inorder
, they are sorted: - symbol values come before string values - alphabetical order for two symbols or two strings
function composeInterceptors
composeInterceptors: <C extends Context = Context>( ...interceptors: GenericInterceptorOrKey<C>[]) => GenericInterceptor<C>;
Compose a list of interceptors as a single interceptor
Parameter interceptors
A list of interceptor functions or binding keys
function config
config: typeof config;
Inject a property from
config
of the current binding. If no corresponding config value is present,undefined
will be injected as the configuration binding is resolved withoptional: true
by default.Parameter propertyPath
Optional property path of the config. If is
''
or not present, theconfig
object will be returned.Parameter metadata
Optional metadata to help the injection
Example 1
class Store {constructor(@config('x') public optionX: number,@config('y') public optionY: string,) { }}ctx.configure('store1', { x: 1, y: 'a' });ctx.configure('store2', { x: 2, y: 'b' });ctx.bind('store1').toClass(Store);ctx.bind('store2').toClass(Store);const store1 = ctx.getSync('store1');expect(store1.optionX).to.eql(1);expect(store1.optionY).to.eql('a');const store2 = ctx.getSync('store2');expect(store2.optionX).to.eql(2);expect(store2.optionY).to.eql('b');
function configBindingKeyFor
configBindingKeyFor: <ConfigValueType = unknown>( key: BindingAddress, propertyPath?: string) => BindingKey<ConfigValueType>;
Create binding key for configuration of the binding
Parameter key
Binding key for the target binding
Parameter propertyPath
Property path for the configuration
function createBindingFromClass
createBindingFromClass: <T>( cls: Constructor<T | Provider<T>> | DynamicValueProviderClass<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)
: ifcls
is a plain class such asMyController
-binding.toProvider(cls)
: ifcls
is a value provider class with a prototype methodvalue()
-binding.toDynamicValue(cls)
: ifcls
is a dynamic value provider class with a static methodvalue()
Parameter cls
A class. It can be either a plain class, a value provider class, or a dynamic value provider class
Parameter options
Options to customize the binding key
function createProxyWithInterceptors
createProxyWithInterceptors: <T extends object>( target: T, context?: Context, session?: ResolutionSession, source?: InvocationSource) => AsyncProxy<T>;
Create a proxy that applies interceptors for method invocations
Parameter target
Target class or object
Parameter context
Context object
Parameter session
Resolution session
Parameter source
Invocation source
function createViewGetter
createViewGetter: { <T = unknown>( ctx: Context, bindingFilter: BindingFilter, session?: ResolutionSession ): Getter<T[]>; <T = unknown>( ctx: Context, bindingFilter: BindingFilter, bindingComparator?: BindingComparator, session?: ResolutionOptionsOrSession ): Getter<T[]>;};
Create a context view as a getter with the given filter
Parameter ctx
Context object
Parameter bindingFilter
A function to match bindings
Parameter session
Resolution session
Create a context view as a getter with the given filter and sort matched bindings by the comparator.
Parameter ctx
Context object
Parameter bindingFilter
A function to match bindings
Parameter bindingComparator
A function to compare two bindings
Parameter session
Resolution session
function describeInjectedArguments
describeInjectedArguments: ( target: Object, method?: string) => Readonly<Injection>[];
Return an array of injection objects for parameters
Parameter target
The target class for constructor or static methods, or the prototype for instance methods
Parameter method
Method name, undefined for constructor
function describeInjectedProperties
describeInjectedProperties: ( target: Object) => MetadataMap<Readonly<Injection<any>>>;
Return a map of injection objects for properties
Parameter target
The target class for static properties or prototype for instance properties.
function filterByKey
filterByKey: (keyPattern?: string | RegExp | BindingFilter) => BindingFilter;
Create a binding filter from key pattern
Parameter keyPattern
Binding key/wildcard, regexp, or a filter function
function filterByTag
filterByTag: (tagPattern: BindingTag | RegExp) => BindingTagFilter;
Create a binding filter for the tag pattern
Parameter tagPattern
Binding tag name, regexp, or object
function getBindingMetadata
getBindingMetadata: <T = unknown>( target: Function) => BindingMetadata<T> | undefined;
Get binding metadata for a class
Parameter target
The target class
function getDeepProperty
getDeepProperty: <OUT = any, IN = any>( value: IN, path: string) => OUT | undefined;
Get nested properties of an object by path
Parameter value
Value of the source object
Parameter path
Path to the property
function globalInterceptor
globalInterceptor: (group?: string, ...specs: BindingSpec[]) => ClassDecorator;
@globalInterceptor
decorator to mark the class as a global interceptorParameter group
Group for ordering the interceptor
Parameter specs
Extra binding specs
function hasInjections
hasInjections: (cls: Constructor<unknown>) => boolean;
Check if the given class has
@inject
or other decorations that map to@inject
.Parameter cls
Class with possible
@inject
decorations
function includesTagValue
includesTagValue: (...itemValues: unknown[]) => TagValueMatcher;
Create a tag value matcher function that returns
true
if the target tag value equals to the item value or is an array that includes the item value.Parameter itemValues
A list of tag item value
function inject
inject: typeof inject;
A decorator to annotate method arguments for automatic injection by LoopBack IoC container.
Parameter bindingSelector
What binding to use in order to resolve the value of the decorated constructor parameter or property.
Parameter metadata
Optional metadata to help the injection
Parameter resolve
Optional function to resolve the injection
Example 1
Usage - Typescript:
class InfoController {@inject('authentication.user') public userName: string;constructor(@inject('application.name') public appName: string) {}// ...}Usage - JavaScript:
- TODO(bajtos)
function injectable
injectable: typeof injectable;
Decorate a class with binding configuration
Parameter specs
A list of binding scope/tags or template functions to configure the binding
Example 1
@injectable((binding) => {binding.inScope(BindingScope.SINGLETON).tag('controller')})@injectable({scope: BindingScope.SINGLETON})export class MyController {}
function inspectInjections
inspectInjections: (binding: Readonly<Binding<unknown>>) => JSONObject;
Inspect injections for a binding created with
toClass
ortoProvider
Parameter binding
Binding object
function inspectTargetType
inspectTargetType: (injection: Readonly<Injection>) => Function | undefined;
Inspect the target type for the injection to find out the corresponding JavaScript type
Parameter injection
Injection information
function instantiateClass
instantiateClass: <T extends object>( 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.
Parameter ctor
The class constructor to call.
Parameter ctx
The context containing values for
@inject
resolutionParameter session
Optional session for binding and dependency resolution
Parameter nonInjectedArgs
Optional array of args for non-injected parameters
function intercept
intercept: ( ...interceptorOrKeys: InterceptorOrKey[]) => ( target: any, method?: string, methodDescriptor?: TypedPropertyDescriptor<any>) => any;
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 ofinterceptor
functions or binding keys.Parameter interceptorOrKeys
One or more interceptors or binding keys that are resolved to be interceptors
Example 1
@intercept(log, metrics)class MyController {@intercept('caching-interceptor')@intercept('name-validation-interceptor')greet(name: string) {return `Hello, ${name}`;}}
function invokeInterceptors
invokeInterceptors: <C extends Context = Context, T = any>( context: C, interceptors: GenericInterceptorOrKey<C>[]) => ValueOrPromise<T | undefined>;
Invoke a chain of interceptors with the context
Parameter context
Context object
Parameter interceptors
An array of interceptor functions or binding keys
function invokeMethod
invokeMethod: ( target: object, method: string, ctx: Context, nonInjectedArgs?: InvocationArgs, options?: InvocationOptions) => ValueOrPromise<InvocationResult>;
Invoke a method using dependency injection. Interceptors are invoked as part of the invocation.
Parameter target
Target of the method, it will be the class for a static method, and instance or class prototype for a prototype method
Parameter method
Name of the method
Parameter ctx
Context object
Parameter nonInjectedArgs
Optional array of args for non-injected parameters
Parameter options
Options for the invocation
function invokeMethodWithInterceptors
invokeMethodWithInterceptors: ( context: Context, target: object, methodName: string, args: InvocationArgs, options?: InvocationOptions) => ValueOrPromise<InvocationResult>;
Invoke a method with the given context
Parameter context
Context object
Parameter target
Target class (for static methods) or object (for instance methods)
Parameter methodName
Method name
Parameter args
An array of argument values
Parameter options
Options for the invocation
function isBindingAddress
isBindingAddress: ( bindingSelector: BindingSelector) => bindingSelector is BindingAddress<unknown>;
Type guard for binding address
Parameter bindingSelector
Binding key or filter function
function isBindingTagFilter
isBindingTagFilter: (filter?: BindingFilter) => filter is BindingTagFilter;
Type guard for BindingTagFilter
Parameter filter
A BindingFilter function
function isDynamicValueProviderClass
isDynamicValueProviderClass: <T = unknown>( factory: unknown) => factory is DynamicValueProviderClass<T>;
Check if the factory is a value factory provider class
Parameter factory
A factory function or a dynamic value provider class
function isPromiseLike
isPromiseLike: <T>( value: T | PromiseLike<T> | undefined) => value is PromiseLike<T>;
Check whether a value is a Promise-like instance. Recognizes both native promises and third-party promise libraries.
Parameter value
The value to check.
function isProviderClass
isProviderClass: <T>(cls: unknown) => cls is Constructor<Provider<T>>;
Check if a class implements
Provider
interfaceParameter cls
A class
function mergeInterceptors
mergeInterceptors: ( interceptorsFromSpec: InterceptorOrKey[], existingInterceptors: InterceptorOrKey[]) => InterceptorOrKey[];
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]
Parameter interceptorsFromSpec
Interceptors from
@intercept
Parameter existingInterceptors
Interceptors already applied for the method
function registerInterceptor
registerInterceptor: ( ctx: Context, interceptor: Interceptor | Constructor<Provider<Interceptor>>, options?: InterceptorBindingOptions) => Binding<Interceptor>;
Register an interceptor function or provider class to the given context
Parameter ctx
Context object
Parameter interceptor
An interceptor function or provider class
Parameter options
Options for the interceptor binding
function removeNameAndKeyTags
removeNameAndKeyTags: (binding: Binding<unknown>) => void;
A binding template function to delete
name
andkey
tags
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 inctx
.The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.
Parameter target
The class for constructor injection or prototype for method injection
Parameter method
The method name. If set to '', the constructor will be used.
Parameter ctx
The context containing values for
@inject
resolutionParameter session
Optional session for binding and dependency resolution
Parameter nonInjectedArgs
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 inctx
.The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.
Parameter constructor
The class for which properties should be resolved.
Parameter ctx
The context containing values for
@inject
resolutionParameter session
Optional session for binding and dependency resolution
function resolveList
resolveList: <T, V>( list: T[], resolver: (val: T, index: number, values: 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.Parameter list
The original array containing the source entries
Parameter resolver
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.
Example 1
- Example 1: resolve all entries synchronously
const result = resolveList(['a', 'b'], v => v.toUpperCase());The
result
will be['A', 'B']
.- Example 2: resolve one or more entries asynchronously
const result = resolveList(['a', 'b'], v =>Promise.resolve(v.toUpperCase()),);The
result
will be a promise of['A', 'B']
.
function resolveMap
resolveMap: <T, V>( map: MapObject<T>, resolver: (val: T, key: string, values: 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.Parameter map
The original object containing the source entries
Parameter resolver
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.
Example 1
- Example 1: resolve all entries synchronously
const result = resolveMap({a: 'x', b: 'y'}, v => v.toUpperCase());The
result
will be{a: 'X', b: 'Y'}
.- Example 2: resolve one or more entries asynchronously
const result = resolveMap({a: 'x', b: 'y'}, v =>Promise.resolve(v.toUpperCase()),);The
result
will be a promise of{a: 'X', b: 'Y'}
.
function resolveUntil
resolveUntil: <T, V>( 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
Parameter source
The iterator of source values
Parameter resolver
The resolve function that maps the source value to a result
Parameter evaluator
The evaluate function that decides when to stop
function sortBindingsByPhase
sortBindingsByPhase: <T = unknown>( bindings: Readonly<Binding<T>>[], phaseTagName?: string, orderOfPhases?: (string | symbol)[]) => Readonly<Binding<T>>[];
Sort bindings by phase names denoted by a tag and the predefined order
Parameter bindings
An array of bindings
Parameter phaseTagName
Tag name for phase, for example, we can use the value
'a'
of tagorder
as the phase name forbinding.tag({order: 'a'})
.Parameter orderOfPhases
An array of phase names as the predefined order
function transformValueOrPromise
transformValueOrPromise: <T, V>( 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
Parameter valueOrPromise
The value or promise
Parameter transformer
A function that maps the source value to a value or promise
function tryCatchFinally
tryCatchFinally: <T>( action: () => ValueOrPromise<T>, errorAction?: (err: unknown) => T | never, finalAction?: () => void) => ValueOrPromise<T>;
Try to run an action that returns a promise or a value with error and final actions to mimic
try {} catch(err) {} finally {}
for a value or promise.Parameter action
A function that returns a promise or a value
Parameter errorAction
A function to be called once the action is rejected (synchronously or asynchronously). It must either return a new value or throw an error.
Parameter finalAction
A function to be called once the action is fulfilled or rejected (synchronously or asynchronously)
function tryWithFinally
tryWithFinally: <T>( action: () => ValueOrPromise<T>, finalAction: () => void) => ValueOrPromise<T>;
Try to run an action that returns a promise or a value
Parameter action
A function that returns a promise or a value
Parameter finalAction
A function to be called once the action is fulfilled or rejected (synchronously or asynchronously)
function uuid
uuid: () => string;
A utility to generate uuid v4
Deprecated
Use
generateUniqueId
, [uuid](https://www.npmjs.com/package/uuid) or [hyperid](https://www.npmjs.com/package/hyperid) instead.
Classes
class Binding
class Binding<T = BoundValue> extends EventEmitter {}
Binding represents an entry in the
Context
. Each binding has a key and a corresponding value getter.
constructor
constructor(key: BindingAddress<T>, isLocked?: boolean);
property isLocked
isLocked: boolean;
property key
readonly key: string;
Key of the binding
property providerConstructor
readonly providerConstructor: Constructor<Provider<T>>;
For bindings bound via
toProvider()
, this property contains the constructor function of the provider class
property scope
readonly scope: BindingScope;
Scope of the binding to control how the value is cached/shared
property source
readonly source: BindingSource<T>;
property tagMap
readonly tagMap: TagMap;
Map for tag name/value pairs
property tagNames
readonly tagNames: string[];
Get an array of tag names
property type
readonly type: BindingType;
Type of the binding value getter
property valueConstructor
readonly valueConstructor: Constructor<T>;
For bindings bound via
toClass()
, this property contains the constructor function of the class
method apply
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.
Parameter templateFns
One or more functions to configure the binding
Example 1
const serverTemplate = (binding: Binding) =>binding.inScope(BindingScope.SINGLETON).tag('server');const serverBinding = new Binding<RestServer>('servers.RestServer1');serverBinding.apply(serverTemplate);
method applyDefaultScope
applyDefaultScope: (scope: BindingScope) => this;
Apply default scope to the binding. It only changes the scope if it's not set yet
Parameter scope
Default binding scope
method bind
static bind: <V = unknown>(key: BindingAddress<V>) => Binding<V>;
A static method to create a binding so that we can do
Binding.bind('foo').to('bar');
asnew Binding('foo').to('bar')
is not easy to read.Parameter key
Binding key
method configure
static configure: <V = unknown>(key: BindingAddress) => Binding<V>;
Create a configuration binding for the given key
Parameter key
Key for the binding to be configured
Example 1
const configBinding = Binding.configure('servers.RestServer.server1').to({port: 3000});
method getValue
getValue: { (ctx: Context, session?: ResolutionSession): ValueOrPromise<T>; (ctx: Context, options?: ResolutionOptions): ValueOrPromise<T>;};
This is an internal function optimized for performance. Users should use
@inject(key)
orctx.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 valueConsumers wishing to consume sync values directly should use
isPromiseLike
to check the type of the returned value to decide how to handle it.Parameter ctx
Context for the resolution
Parameter session
Optional session for binding and dependency resolution
Example 1
const result = binding.getValue(ctx);if (isPromiseLike(result)) {result.then(doSomething)} else {doSomething(result);}Returns a value or promise for this binding in the given context. The resolved value can be
undefined
ifoptional
is set totrue
inoptions
.Parameter ctx
Context for the resolution
Parameter options
Optional options for binding and dependency resolution
method inScope
inScope: (scope: BindingScope) => this;
Set the binding scope
Parameter scope
Binding scope
method inspect
inspect: (options?: BindingInspectOptions) => JSONObject;
Inspect the binding to return a json representation of the binding information
Parameter options
Options to control what information should be included
method lock
lock: () => this;
Lock the binding so that it cannot be rebound
method on
on: { (eventName: 'changed', listener: BindingEventListener): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
The "changed" event is emitted by methods such as
tag
,inScope
,to
, andtoClass
.Parameter eventName
The name of the event - always
changed
.Parameter listener
The listener function to call when the event is emitted.
method once
once: { (eventName: 'changed', listener: BindingEventListener): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
The "changed" event is emitted by methods such as
tag
,inScope
,to
, andtoClass
.Parameter eventName
The name of the event - always
changed
.Parameter listener
The listener function to call when the event is emitted.
method refresh
refresh: (ctx: Context) => void;
Invalidate the binding cache so that its value will be reloaded next time. This is useful to force reloading a cached value when its configuration or dependencies are changed. **WARNING**: The state held in the cached value will be gone.
Parameter ctx
Context object
method tag
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.
Parameter tags
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
Example 1
// Add a named tag `controller`binding.tag('controller');// Add two named tags: `controller` and `rest`binding.tag('controller', 'rest');// Add two tags// - `controller` (name = 'controller')// `{name: 'my-controller'}` (name = 'name', value = 'my-controller')binding.tag('controller', {name: 'my-controller'});
method to
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.
Parameter value
The bound value.
Example 1
ctx.bind('appName').to('CodeHub');
method toAlias
toAlias: (keyWithPath: BindingAddress<T>) => this;
Bind the key to an alias of another binding
Parameter keyWithPath
Target binding key with optional path, such as
servers.RestServer.options#apiExplorer
method toClass
toClass: <C extends T & object>(ctor: Constructor<C>) => this;
Bind the key to an instance of the given class.
Parameter ctor
The class constructor to call. Any constructor arguments must be annotated with
@inject
so that we can resolve them from the context.
method toDynamicValue
toDynamicValue: ( factory: ValueFactory<T> | DynamicValueProviderClass<T>) => this;
Bind the key to a computed (dynamic) value.
Parameter factoryFn
The factory function creating the value. Both sync and async functions are supported.
Example 1
// synchronousctx.bind('now').toDynamicValue(() => Date.now());// asynchronousctx.bind('something').toDynamicValue(async () => Promise.delay(10).then(doSomething));
method toInjectable
toInjectable: ( ctor: DynamicValueProviderClass<T> | Constructor<T | Provider<T>>) => this;
Bind to a class optionally decorated with
@injectable
. Based on the introspection of the class, it callstoClass/toProvider/toDynamicValue
internally. The current binding key will be preserved (not being overridden by the key inferred from the class or options).This is similar to createBindingFromClass but applies to an existing binding.
Parameter ctor
A class decorated with
@injectable
.Example 1
@injectable({scope: BindingScope.SINGLETON, tags: {service: 'MyService}})class MyService {// ...}const ctx = new Context();ctx.bind('services.MyService').toInjectable(MyService);
method toJSON
toJSON: () => JSONObject;
Convert to a plain JSON object
method toProvider
toProvider: (providerClass: Constructor<Provider<T>>) => this;
Bind the key to a value computed by a Provider.
*
Parameter provider
The value provider to use.
Example 1
export class DateProvider implements Provider<Date> {constructor(@inject('stringDate') private param: String){}value(): Date {return new Date(param);}}
method unlock
unlock: () => this;
Unlock the binding
class BindingKey
class BindingKey<ValueType> {}
property CONFIG_NAMESPACE
static CONFIG_NAMESPACE: string;
Name space for configuration binding keys
property key
readonly key: string;
property PROPERTY_SEPARATOR
static readonly PROPERTY_SEPARATOR: string;
property propertyPath
readonly propertyPath?: string;
method buildKeyForConfig
static buildKeyForConfig: <T>(key?: BindingAddress) => BindingAddress<T>;
Build a binding key for the configuration of the given binding. The format is
<key>:$config
Parameter key
Key of the target binding to be configured
method create
static create: <V>(key: string, propertyPath?: string) => BindingKey<V>;
Create a new key for a binding bound to a value of type
ValueType
.Parameter key
The binding key. When propertyPath is not provided, the key is allowed to contain propertyPath as encoded via
BindingKey#toString()
Parameter propertyPath
Optional path to a deep property of the bound value.
Example 1
BindingKey.create<string>('application.name');BindingKey.create<number>('config', 'rest.port);BindingKey.create<number>('config#rest.port');
method deepProperty
deepProperty: <PropertyValueType>( propertyPath: string) => BindingKey<PropertyValueType>;
Get a binding address for retrieving a deep property of the object bound to the current binding key.
Parameter propertyPath
A dot-separated path to a (deep) property, e.g. "server.port".
method generate
static generate: <T>(namespace?: string) => BindingKey<T>;
Generate a universally unique binding key.
Please note the format of they generated key is not specified, you must not rely on any specific formatting (e.g. UUID style).
Parameter namespace
Namespace for the binding
method parseKeyWithPath
static parseKeyWithPath: <T>(keyWithPath: BindingAddress<T>) => BindingKey<T>;
Parse a string containing both the binding key and the path to the deeply nested property to retrieve.
Parameter keyWithPath
The key with an optional path, e.g. "application.instance" or "config#rest.port".
method toString
toString: () => string;
method validate
static validate: <T>(key: BindingAddress<T>) => string;
Validate the binding key format. Please note that
#
is reserved. Returns a string representation of the binding key.Parameter key
Binding key, such as
a
,a.b
,a:b
, ora/b
class Context
class Context extends EventEmitter {}
Context provides an implementation of Inversion of Control (IoC) container
constructor
constructor(_parent?: string | Context, name?: string);
Create a new context.
Parameter _parent
The optional parent context
Parameter name
Name of the context. If not provided, a unique identifier will be generated as the name.
Example 1
// Create a new root context, let the framework to create a unique nameconst rootCtx = new Context();// Create a new child context inheriting bindings from `rootCtx`const childCtx = new Context(rootCtx);// Create another root context called "application"const appCtx = new Context('application');// Create a new child context called "request" and inheriting bindings// from `appCtx`const reqCtx = new Context(appCtx, 'request');
property configResolver
protected configResolver: ConfigurationResolver;
Configuration resolver
property name
readonly name: string;
Name of the context
property registry
protected readonly registry: Map<string, Binding<any>>;
Key to binding map as the internal registry
property scope
scope: BindingScope;
Scope for binding resolution
property subscriptionManager
readonly subscriptionManager: ContextSubscriptionManager;
Manager for observer subscriptions
property tagIndexer
protected readonly tagIndexer: ContextTagIndexer;
Indexer for bindings by tag
method add
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.
Parameter binding
The configured binding to be added
method bind
bind: <ValueType = any>(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.
Parameter key
Binding key
method close
close: () => void;
Close the context: clear observers, stop notifications, and remove event listeners from its parent context.
Remarks
This method MUST be called to avoid memory leaks once a context object is no longer needed and should be recycled. An example is the
RequestContext
, which is created per request.
method configure
configure: <ConfigValueType = any>( 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 bindingcontrollers.MyController:$config
with value{x: 1}
.Parameter key
The key for the binding to be configured
method contains
contains: (key: BindingAddress) => boolean;
Check if a binding exists with the given key in the local context without delegating to the parent context
Parameter key
Binding key
method createView
createView: <T = unknown>( filter: BindingFilter, comparator?: BindingComparator, options?: Omit<ResolutionOptions, 'session'>) => ContextView<T>;
Create a view of the context chain with the given binding filter
Parameter filter
A function to match bindings
Parameter comparator
A function to sort matched bindings
Parameter options
Resolution options
method debug
protected debug: (...args: unknown[]) => void;
Wrap the debug statement so that it always print out the context name as the prefix
Parameter args
Arguments for the debug
method emitError
emitError: (err: unknown) => void;
Emit an
error
eventParameter err
Error
method emitEvent
emitEvent: <T extends ContextEvent>(type: string, event: T) => void;
A strongly-typed method to emit context events
Parameter type
Event type
Parameter event
Context event
method find
find: <ValueType = any>( pattern?: string | RegExp | BindingFilter) => Readonly<Binding<ValueType>>[];
Find bindings using a key pattern or filter function
Parameter pattern
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 - returnfalse
to exclude it.
method findByTag
findByTag: <ValueType = any>( 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.
Parameter tagFilter
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'}
method findOrCreateBinding
findOrCreateBinding: <T>( key: BindingAddress<T>, policy?: BindingCreationPolicy) => Binding<T>;
Find or create a binding for the given key
Parameter key
Binding address
Parameter policy
Binding creation policy
method get
get: { <ValueType>( keyWithPath: BindingAddress<ValueType>, session?: ResolutionSession ): Promise<ValueType>; <ValueType>( keyWithPath: BindingAddress<ValueType>, options: ResolutionOptions ): Promise<ValueType>;};
Get the value bound to the given key, throw an error when no value is bound for the given key.
Parameter keyWithPath
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Parameter session
Optional session for resolution (accepted for backward compatibility)
Returns
A promise of the bound value.
Example 1
// get the value bound to "application.instance"const app = await ctx.get<Application>('application.instance');// get "rest" property from the value bound to "config"const config = await ctx.get<RestComponentConfig>('config#rest');// get "a" property of "numbers" property from the value bound to "data"ctx.bind('data').to({numbers: {a: 1, b: 2}, port: 3000});const a = await ctx.get<number>('data#numbers.a');Get the value bound to the given key, optionally return a (deep) property of the bound value.
Parameter keyWithPath
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Parameter options
Options for resolution.
Returns
A promise of the bound value, or a promise of undefined when the optional binding is not found.
Example 1
// get "rest" property from the value bound to "config"// use `undefined` when no config is providedconst config = await ctx.get<RestComponentConfig>('config#rest', {optional: true});
method getBinding
getBinding: { <ValueType = any>(key: BindingAddress<ValueType>): Binding<ValueType>; <ValueType>( key: BindingAddress<ValueType>, options?: { optional?: boolean } ): 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.
Parameter key
Binding key
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.Parameter key
Binding key
Parameter options
Options to control if the binding is optional. If
options.optional
is set to true, the method will returnundefined
instead of throwing an error if the binding key is not found.
method getConfig
getConfig: <ConfigValueType>( key: BindingAddress, propertyPath?: string, resolutionOptions?: ResolutionOptions) => Promise<ConfigValueType | undefined>;
Resolve configuration for the binding by key
Parameter key
Binding key
Parameter propertyPath
Property path for the option. For example,
x.y
requests for<config>.x.y
. If not set, the<config>
object will be returned.Parameter resolutionOptions
Options for the resolution.
method getConfigAsValueOrPromise
getConfigAsValueOrPromise: <ConfigValueType>( key: BindingAddress, propertyPath?: string, resolutionOptions?: ResolutionOptions) => ValueOrPromise<ConfigValueType | undefined>;
Get the value or promise of configuration for a given binding by key
Parameter key
Binding key
Parameter propertyPath
Property path for the option. For example,
x.y
requests for<config>.x.y
. If not set, the<config>
object will be returned.Parameter resolutionOptions
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.
method getConfigSync
getConfigSync: <ConfigValueType>( key: BindingAddress, propertyPath?: string, resolutionOptions?: ResolutionOptions) => ConfigValueType | undefined;
Resolve configuration synchronously for the binding by key
Parameter key
Binding key
Parameter propertyPath
Property path for the option. For example,
x.y
requests forconfig.x.y
. If not set, theconfig
object will be returned.Parameter resolutionOptions
Options for the resolution.
method getDebugNamespace
protected getDebugNamespace: () => string;
Get the debug namespace for the context class. Subclasses can override this method to supply its own namespace.
Example 1
export class Application extends Context {super('application');}protected getDebugNamespace() {return 'loopback:context:application';}
method getOwnerContext
getOwnerContext: ( keyOrBinding: BindingAddress | Readonly<Binding<unknown>>) => Context | undefined;
Get the owning context for a binding or its key
Parameter keyOrBinding
Binding object or key
method getResolutionContext
getResolutionContext: ( binding: Readonly<Binding<unknown>>) => Context | undefined;
Locate the resolution context for the given binding. Only bindings in the resolution context and its ancestors are visible as dependencies to resolve the given binding
Parameter binding
Binding object
method getScopedContext
getScopedContext: ( scope: BindingScope.APPLICATION | BindingScope.SERVER | BindingScope.REQUEST) => Context | undefined;
Get the context matching the scope
Parameter scope
Binding scope
method getSync
getSync: { <ValueType>( keyWithPath: BindingAddress<ValueType>, session?: ResolutionSession ): ValueType; <ValueType>( keyWithPath: BindingAddress<ValueType>, options?: ResolutionOptions ): 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.
Parameter keyWithPath
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Parameter session
Session for resolution (accepted for backward compatibility)
Returns
A promise of the bound value.
Example 1
// get the value bound to "application.instance"const app = ctx.getSync<Application>('application.instance');// get "rest" property from the value bound to "config"const config = await ctx.getSync<RestComponentConfig>('config#rest');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.
Parameter keyWithPath
The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.
Parameter options
Options for resolution.
Returns
The bound value, or undefined when an optional binding is not found.
Example 1
// get "rest" property from the value bound to "config"// use "undefined" when no config is providedconst config = await ctx.getSync<RestComponentConfig>('config#rest', {optional: true});
method inspect
inspect: (options?: ContextInspectOptions) => JSONObject;
Inspect the context and dump out a JSON object representing the context hierarchy
Parameter options
Options for inspect
method isBound
isBound: (key: BindingAddress) => boolean;
Check if a key is bound in the context or its ancestors
Parameter key
Binding key
method isSubscribed
isSubscribed: (observer: ContextObserver) => boolean;
Check if an observer is subscribed to this context
Parameter observer
Context observer
method isVisibleTo
isVisibleTo: (ctx: Context) => boolean;
Check if this context is visible (same or ancestor) to the given one
Parameter ctx
Another context object
method on
on: { (eventName: 'bind' | 'unbind', listener: ContextEventListener): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.
Parameter eventName
The name of the event - always
bind
orunbind
.Parameter listener
The listener function to call when the event is emitted.
method once
once: { (eventName: 'bind' | 'unbind', listener: ContextEventListener): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
The "bind" event is emitted when a new binding is added to the context. The "unbind" event is emitted when an existing binding is removed.
Parameter eventName
The name of the event - always
bind
orunbind
.Parameter listener
The listener function to call when the event is emitted.
method setupConfigurationResolverIfNeeded
protected setupConfigurationResolverIfNeeded: () => ConfigurationResolver;
Set up the configuration resolver if needed
method subscribe
subscribe: (observer: ContextEventObserver) => Subscription;
Add a context event observer to the context
Parameter observer
Context observer instance or function
method toJSON
toJSON: () => JSONObject;
Create a plain JSON object for the context
method unbind
unbind: (key: BindingAddress) => boolean;
Unbind a binding from the context. No parent contexts will be checked.
Parameter key
Binding key
Returns
true if the binding key is found and removed from this context
Remarks
If you need to unbind a binding owned by a parent context, use the code below:
const ownerCtx = ctx.getOwnerContext(key);return ownerCtx != null && ownerCtx.unbind(key);
method unsubscribe
unsubscribe: (observer: ContextEventObserver) => boolean;
Remove the context event observer from the context
Parameter observer
Context event observer
class ContextSubscriptionManager
class ContextSubscriptionManager extends EventEmitter {}
Manager for context observer subscriptions
constructor
constructor(context: Context);
property context
protected readonly context: Context;
method close
close: () => void;
Close the context: clear observers, stop notifications, and remove event listeners from its parent context.
Remarks
This method MUST be called to avoid memory leaks once a context object is no longer needed and should be recycled. An example is the
RequestContext
, which is created per request.
method isSubscribed
isSubscribed: (observer: ContextObserver) => boolean;
Check if an observer is subscribed to this context
Parameter observer
Context observer
method notifyObservers
protected notifyObservers: ( event: ContextEvent, observers?: Set<ContextEventObserver> | undefined) => Promise<void>;
Publish an event to the registered observers. Please note the notification is queued and performed asynchronously so that we allow fluent APIs such as
ctx.bind('key').to(...).tag(...);
and give observers the fully populated binding.Parameter event
Context event
Parameter observers
Current set of context observers
method subscribe
subscribe: (observer: ContextEventObserver) => Subscription;
Add a context event observer to the context
Parameter observer
Context observer instance or function
method unsubscribe
unsubscribe: (observer: ContextEventObserver) => boolean;
Remove the context event observer from the context
Parameter observer
Context event observer
method waitUntilPendingNotificationsDone
waitUntilPendingNotificationsDone: (timeout?: number) => Promise<void>;
Wait until observers are notified for all of currently pending notification events.
This method is for test only to perform assertions after observers are notified for relevant events.
class ContextView
class ContextView<T = unknown> extends EventEmitter implements ContextObserver {}
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: - 'bind': when a binding is added to the view - 'unbind': when a binding is removed from the view - '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
constructor( context: Context, filter: BindingFilter, comparator?: BindingComparator, resolutionOptions?: Omit<ResolutionOptions, 'session'>);
Create a context view
Parameter context
Context object to watch
Parameter filter
Binding filter to match bindings of interest
Parameter comparator
Comparator to sort the matched bindings
property bindings
readonly bindings: Readonly<Binding<T>>[];
Get the list of matched bindings. If they are not cached, it tries to find them from the context.
property comparator
readonly comparator?: BindingComparator;
property context
readonly context: Context;
property filter
readonly filter: BindingFilter;
method asGetter
asGetter: (session?: ResolutionOptionsOrSession) => Getter<T[]>;
As a
Getter
function
method close
close: () => void;
Stop listening events from the context
method findBindings
protected findBindings: () => Readonly<Binding<T>>[];
Find matching bindings and refresh the cache
method observe
observe: ( event: ContextEventType, binding: Readonly<Binding<unknown>>, context: Context) => void;
Listen on
bind
orunbind
and invalidate the cache
method on
on: { (eventName: 'bind', listener: <V>(event: ContextViewEvent<V>) => void): this; ( eventName: 'unbind', listener: <V>(event: ContextViewEvent<V> & { cachedValue?: V }) => void ): this; (eventName: 'refresh', listener: () => void): this; (eventName: 'refresh', listener: <V>(result: V[]) => void): this; (eventName: 'close', listener: () => void): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
The "bind" event is emitted when a new binding is added to the view.
Parameter eventName
The name of the event - always
bind
.Parameter listener
The listener function to call when the event is emitted.
The "unbind" event is emitted a new binding is removed from the view.
Parameter eventName
The name of the event - always
unbind
.Parameter listener
The listener function to call when the event is emitted.
The "refresh" event is emitted when the view is refreshed as bindings are added/removed.
Parameter eventName
The name of the event - always
refresh
.Parameter listener
The listener function to call when the event is emitted.
The "resolve" event is emitted when the cached values are resolved and updated.
Parameter eventName
The name of the event - always
refresh
.Parameter listener
The listener function to call when the event is emitted.
The "close" event is emitted when the view is closed (stopped observing context events)
Parameter eventName
The name of the event - always
close
.Parameter listener
The listener function to call when the event is emitted.
method once
once: { (eventName: 'bind', listener: <V>(event: ContextViewEvent<V>) => void): this; ( eventName: 'unbind', listener: <V>(event: ContextViewEvent<V> & { cachedValue?: V }) => void ): this; (eventName: 'refresh', listener: () => void): this; (eventName: 'refresh', listener: <V>(result: V[]) => void): this; (eventName: 'close', listener: () => void): this; (event: string | symbol, listener: (...args: any[]) => void): this;};
The "bind" event is emitted when a new binding is added to the view.
Parameter eventName
The name of the event - always
bind
.Parameter listener
The listener function to call when the event is emitted.
The "unbind" event is emitted a new binding is removed from the view.
Parameter eventName
The name of the event - always
unbind
.Parameter listener
The listener function to call when the event is emitted.
The "refresh" event is emitted when the view is refreshed as bindings are added/removed.
Parameter eventName
The name of the event - always
refresh
.Parameter listener
The listener function to call when the event is emitted.
The "resolve" event is emitted when the cached values are resolved and updated.
Parameter eventName
The name of the event - always
refresh
.Parameter listener
The listener function to call when the event is emitted.
The "close" event is emitted when the view is closed (stopped observing context events)
Parameter eventName
The name of the event - always
close
.Parameter listener
The listener function to call when the event is emitted.
method open
open: () => Subscription | undefined;
Start listening events from the context
method refresh
refresh: () => void;
Refresh the view by invalidating its cache
method resolve
resolve: (session?: ResolutionOptionsOrSession) => ValueOrPromise<T[]>;
Resolve values for the matching bindings
Parameter session
Resolution session
method singleValue
singleValue: (session?: ResolutionOptionsOrSession) => Promise<T | undefined>;
Get the single value
method values
values: (session?: ResolutionOptionsOrSession) => Promise<T[]>;
Get the list of resolved values. If they are not cached, it tries to find and resolve them.
class DefaultConfigurationResolver
class DefaultConfigurationResolver implements ConfigurationResolver {}
Resolver for configurations of bindings
constructor
constructor(context: Context);
property context
readonly context: Context;
method getConfigAsValueOrPromise
getConfigAsValueOrPromise: <ConfigValueType>( key: BindingAddress<unknown>, propertyPath?: string, resolutionOptions?: ResolutionOptions) => ValueOrPromise<ConfigValueType | undefined>;
class GenericInterceptorChain
class GenericInterceptorChain<C extends Context = Context> {}
A chain of generic interceptors to be invoked for the given context
constructor
constructor(context: Context, interceptors: GenericInterceptorOrKey<C>[]);
Create an invocation chain with a list of interceptor functions or binding keys
Parameter context
Context object
Parameter interceptors
An array of interceptor functions or binding keys
constructor
constructor( context: Context, filter: BindingFilter, comparator?: BindingComparator);
Create an invocation interceptor chain with a binding filter and comparator. The interceptors are discovered from the context using the binding filter and sorted by the comparator (if provided).
Parameter context
Context object
Parameter filter
A binding filter function to select interceptors
Parameter comparator
An optional comparator to sort matched interceptor bindings
property getInterceptors
protected getInterceptors: () => GenericInterceptorOrKey<C>[];
A getter for an array of interceptor functions or binding keys
method asInterceptor
asInterceptor: () => GenericInterceptor<C>;
Use the interceptor chain as an interceptor
method invokeInterceptors
invokeInterceptors: (finalHandler?: Next) => ValueOrPromise<InvocationResult>;
Invoke the interceptor chain
class InterceptedInvocationContext
class InterceptedInvocationContext extends InvocationContext {}
A specialized InvocationContext for interceptors
method getGlobalInterceptorBindingKeys
getGlobalInterceptorBindingKeys: () => string[];
Discover all binding keys for global interceptors (tagged by ContextTags.GLOBAL_INTERCEPTOR)
method loadInterceptors
loadInterceptors: () => InterceptorOrKey[];
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
class InterceptionHandler
class InterceptionHandler<T extends object> implements ProxyHandler<T> {}
A proxy handler that applies interceptors
See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
constructor
constructor( context?: Context, session?: ResolutionSession, source?: InvocationSource<unknown>);
method get
get: (target: T, propertyName: PropertyKey, receiver: unknown) => any;
class InvocationContext
class InvocationContext extends Context {}
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.
constructor
constructor( parent: Context, target: {}, methodName: string, args: InvocationArgs, source?: InvocationSource<unknown>);
Construct a new instance of
InvocationContext
Parameter parent
Parent context, such as the RequestContext
Parameter target
Target class (for static methods) or prototype/object (for instance methods)
Parameter methodName
Method name
Parameter args
An array of arguments
property args
readonly args: InvocationArgs;
property description
readonly description: string;
Description of the invocation
property methodName
readonly methodName: string;
property source
readonly source?: InvocationSource<unknown>;
property target
readonly target: {};
property targetClass
readonly targetClass: Function;
The target class, such as
OrderController
property targetName
readonly targetName: string;
The target name, such as
OrderController.prototype.cancelOrder
method assertMethodExists
assertMethodExists: () => Record<string, Function>;
Assert the method exists on the target. An error will be thrown if otherwise.
Parameter context
Invocation context
method invokeTargetMethod
invokeTargetMethod: (options?: InvocationOptions) => any;
Invoke the target method with the given context
Parameter context
Invocation context
Parameter options
Options for the invocation
method toString
toString: () => string;
class ProxySource
class ProxySource implements InvocationSource<ResolutionSession> {}
Invocation source for injected proxies. It wraps a snapshot of the
ResolutionSession
that tracks the binding/injection stack.
constructor
constructor(value: ResolutionSession);
property type
type: string;
property value
readonly value: ResolutionSession;
method toString
toString: () => string;
class ResolutionError
class ResolutionError extends Error {}
Error for context binding resolutions and dependency injections
constructor
constructor(message: string, resolutionCtx: Partial<ResolutionContext<unknown>>);
property resolutionCtx
readonly resolutionCtx: Partial<ResolutionContext<unknown>>;
class ResolutionSession
class ResolutionSession {}
Object to keep states for a session to resolve bindings and their dependencies within a context
property bindingStack
readonly bindingStack: Readonly<Binding<any>>[];
Getter for bindings on the stack
property currentBinding
readonly currentBinding: Readonly<Binding<any>>;
Getter for the current binding
property currentInjection
readonly currentInjection: Readonly<Injection<any>>;
Getter for the current injection
property injectionStack
readonly injectionStack: Readonly<Injection<any>>[];
Getter for injections on the stack
property stack
readonly stack: ResolutionElement[];
A stack of bindings for the current resolution session. It's used to track the path of dependency resolution and detect circular dependencies.
method describeInjection
static describeInjection: ( injection: Readonly<Injection>) => InjectionDescriptor;
Describe the injection for debugging purpose
Parameter injection
Injection object
method fork
static 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
Parameter session
The current session
method getBindingPath
getBindingPath: () => string;
Get the binding path as
bindingA --> bindingB --> bindingC
.
method getInjectionPath
getInjectionPath: () => string;
Get the injection path as
injectionA --> injectionB --> injectionC
.
method getResolutionPath
getResolutionPath: () => string;
Get the resolution path including bindings and injections, for example: `bindingA --> @ClassA[0] --> bindingB --> @ClassB.prototype.prop1 --> bindingC`.
method popBinding
popBinding: () => Readonly<Binding>;
Exit the resolution of a binding
method popInjection
popInjection: () => Readonly<Injection<any>>;
Pop the last injection
method pushBinding
pushBinding: (binding: Readonly<Binding>) => void;
Enter the resolution of the given binding. If
Parameter binding
Binding
method pushInjection
pushInjection: (injection: Readonly<Injection>) => void;
Push the injection onto the session
Parameter injection
Injection The current injection
method runWithBinding
static runWithBinding: ( action: ResolutionAction, binding: Readonly<Binding>, session?: ResolutionSession) => any;
Run the given action with the given binding and session
Parameter action
A function to do some work with the resolution session
Parameter binding
The current binding
Parameter session
The current resolution session
method runWithInjection
static runWithInjection: ( action: ResolutionAction, injection: Readonly<Injection>, session?: ResolutionSession) => any;
Run the given action with the given injection and session
Parameter action
A function to do some work with the resolution session
Parameter binding
The current injection
Parameter session
The current resolution session
method toString
toString: () => string;
Interfaces
interface BindingComparator
interface BindingComparator {}
Compare function to sort an array of bindings. It is used by
Array.prototype.sort()
.Example 1
const compareByKey: BindingComparator = (a, b) => a.key.localeCompare(b.key);
call signature
( bindingA: Readonly<Binding<unknown>>, bindingB: Readonly<Binding<unknown>>): number;
Compare two bindings
Parameter bindingA
First binding
Parameter bindingB
Second binding
Returns
A number to determine order of bindingA and bindingB - 0 leaves bindingA and bindingB unchanged - <0 bindingA comes before bindingB - >0 bindingA comes after bindingB
interface BindingElement
interface BindingElement {}
Wrapper for bindings tracked by resolution sessions
interface BindingFilter
interface BindingFilter {}
A function that filters bindings. It returns
true
to select a given binding.Remarks
Originally, we allowed filters to be tied with a single value type. This actually does not make much sense - the filter function is typically invoked on all bindings to find those ones matching the given criteria. Filters must be prepared to handle bindings of any value type. We learned about this problem after enabling TypeScript's
strictFunctionTypes
check. This aspect is resolved by typing the input argument asBinding<unknown>
.Ideally,
BindingFilter
should be declared as a type guard as follows:export type BindingFilterGuard<ValueType = unknown> = (binding: Readonly<Binding<unknown>>,) => binding is Readonly<Binding<ValueType>>;But TypeScript treats the following types as incompatible and does not accept type 1 for type 2.
1.
(binding: Readonly<Binding<unknown>>) => boolean
2.(binding: Readonly<Binding<unknown>>) => binding is Readonly<Binding<ValueType>>
If we described BindingFilter as a type-guard, then all filter implementations would have to be explicitly typed as type-guards too, which would make it tedious to write quick filter functions like
b => b.key.startsWith('services')
.To keep things simple and easy to use, we use
boolean
as the return type of a binding filter function.
call signature
(binding: Readonly<Binding<unknown>>): boolean;
interface BindingInspectOptions
interface BindingInspectOptions {}
Options for binding.inspect()
property includeInjections
includeInjections?: boolean;
The flag to control if injections should be inspected
interface BindingTagFilter
interface BindingTagFilter extends BindingFilter {}
Binding filter function that holds a binding tag pattern.
Context.find()
uses thebindingTagPattern
to optimize the matching of bindings by tag to avoid expensive check for all bindings.
property bindingTagPattern
bindingTagPattern: BindingTag | RegExp;
A special property on the filter function to provide access to the binding tag pattern which can be utilized to optimize the matching of bindings by tag in a context.
interface ConfigInjectionMetadata
interface ConfigInjectionMetadata extends InjectionMetadata {}
Injection metadata for
@config.*
property fromBinding
fromBinding?: BindingAddress;
Customize the target binding key from which the configuration is fetched. If not specified, the configuration of the current binding that contains the injection is used.
property propertyPath
propertyPath?: string;
Property path to retrieve the configuration of the target binding, for example,
rest.host
.
interface ConfigurationResolver
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 settingoptional
tofalse
in resolution options.
method getConfigAsValueOrPromise
getConfigAsValueOrPromise: <ConfigValueType>( key: BindingAddress<unknown>, propertyPath?: string, resolutionOptions?: ResolutionOptions) => ValueOrPromise<ConfigValueType | undefined>;
Resolve config for the binding key
Parameter key
Binding key
Parameter propertyPath
Property path for the option. For example,
x.y
requests for<config>.x.y
. If not set, theconfig
object will be returned.Parameter resolutionOptions
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.
interface ContextInspectOptions
interface ContextInspectOptions extends BindingInspectOptions {}
Options for context.inspect()
property includeParent
includeParent?: boolean;
The flag to control if parent context should be inspected
interface ContextObserver
interface ContextObserver {}
Observers of context bind/unbind events
property filter
filter?: BindingFilter;
An optional filter function to match bindings. If not present, the listener will be notified of all binding events.
property observe
observe: ContextObserverFn;
Listen on
bind
,unbind
, or other eventsParameter eventType
Context event type
Parameter binding
The binding as event source
interface ContextViewEvent
interface ContextViewEvent<T> extends ContextEvent {}
An event emitted by a
ContextView
property cachedValue
cachedValue?: T;
Optional cached value for an
unbind
event
interface DynamicValueProviderClass
interface DynamicValueProviderClass<T = unknown> extends Constructor<unknown>, Function {}
A class with a static
value
method as the factory function fortoDynamicValue
.Example 1
import {inject} from '@loopback/context';export class DynamicGreetingProvider {static value(@inject('currentUser') user: string) {return `Hello, ${user}`;}}
property value
value: (...args: BoundValue[]) => ValueOrPromise<T>;
interface InjectBindingMetadata
interface InjectBindingMetadata extends InjectionMetadata {}
Metadata for
@inject.binding
property bindingCreation
bindingCreation?: BindingCreationPolicy;
Controls how the underlying binding is resolved/created
interface Injection
interface Injection<ValueType = BoundValue> {}
Descriptor for an injection point
property bindingSelector
bindingSelector: BindingSelector<ValueType>;
property member
member?: string;
property metadata
metadata: InjectionMetadata;
property methodDescriptorOrParameterIndex
methodDescriptorOrParameterIndex?: TypedPropertyDescriptor<ValueType> | number;
property resolve
resolve?: ResolverFunction;
property target
target: Object;
interface InjectionDescriptor
interface InjectionDescriptor {}
property bindingSelector
bindingSelector: BindingSelector;
property metadata
metadata: InjectionMetadata;
property targetName
targetName: string;
interface InjectionElement
interface InjectionElement {}
Wrapper for injections tracked by resolution sessions
interface InjectionMetadata
interface InjectionMetadata extends Omit<ResolutionOptions, 'session'> {}
An object to provide metadata for
@inject
property bindingComparator
bindingComparator?: BindingComparator;
Optional comparator for matched bindings
property decorator
decorator?: string;
Name of the decorator function, such as
@inject
or@inject.setter
. It's usually set by the decorator implementation.
index signature
[attribute: string]: BoundValue;
Other attributes
interface Interceptor
interface Interceptor extends GenericInterceptor<InvocationContext> {}
Interceptor function to intercept method invocations
interface InterceptorBindingOptions
interface InterceptorBindingOptions extends BindingFromClassOptions {}
Options for an interceptor binding
interface InvocationSource
interface InvocationSource<T = unknown> {}
An interface to represent the caller of the invocation
interface JSONArray
interface JSONArray extends Array<JSONValue> {}
JSON array
interface JSONObject
interface JSONObject extends Record<string, JSONValue> {}
JSON object
interface Notification
interface Notification extends ContextEvent {}
Event data for observer notifications
property observers
observers: Set<ContextEventObserver>;
A snapshot of observers when the original event is emitted
interface Provider
interface Provider<T> {}
Providers allow developers to compute injected values dynamically, with any dependencies required by the value getter injected automatically from the Context.
Example 1
export class DateProvider implements Provider<Date> {constructor(@inject('stringDate') private param: String){}value(): Date {return new Date(param);}}ctx.bind('stringDate').to('2017-01-01')ctx.bind('provider_key').toProvider(DateProvider);const value = ctx.getAsync('provider_key');// value is a Date instance
method value
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.
interface ResolutionContext
interface ResolutionContext<T = unknown> {}
Contextual metadata for resolution
interface ResolutionOptions
interface ResolutionOptions {}
Options for binding/dependency resolution
property asProxyWithInterceptors
asProxyWithInterceptors?: boolean;
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.
property optional
optional?: boolean;
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 returnundefined
instead of throwing an error.
property session
session?: ResolutionSession;
A session to track bindings and injections
interface ResolverFunction
interface ResolverFunction {}
A function to provide resolution of injected values.
Example 1
const resolver: ResolverFunction = (ctx, injection, session) {return session.currentBinding?.key;}
call signature
( ctx: Context, injection: Readonly<Injection>, session: ResolutionSession): ValueOrPromise<BoundValue>;
interface Subscription
interface Subscription {}
Subscription of context events. It's modeled after https://github.com/tc39/proposal-observable.
property closed
closed: boolean;
Is the subscription closed?
method unsubscribe
unsubscribe: () => void;
unsubscribe
interface TagValueMatcher
interface TagValueMatcher {}
A function to check if a given tag value is matched for
filterByTag
call signature
(tagValue: unknown, tagName: string, tagMap: MapObject<unknown>): boolean;
Check if the given tag value matches the search criteria
Parameter tagValue
Tag value from the binding
Parameter tagName
Tag name
Parameter tagMap
Tag map from the binding
Enums
enum BindingCreationPolicy
enum BindingCreationPolicy { ALWAYS_CREATE = 'Always', NEVER_CREATE = 'Never', CREATE_IF_NOT_BOUND = 'IfNotBound',}
Policy to control if a binding should be created for the context
member ALWAYS_CREATE
ALWAYS_CREATE = 'Always'
Always create a binding with the key for the context
member CREATE_IF_NOT_BOUND
CREATE_IF_NOT_BOUND = 'IfNotBound'
Create a binding if the key is not bound in the context. Otherwise, return the existing binding.
member NEVER_CREATE
NEVER_CREATE = 'Never'
Never create a binding for the context. If the key is not bound in the context, throw an error.
enum BindingScope
enum BindingScope { TRANSIENT = 'Transient', CONTEXT = 'Context', SINGLETON = 'Singleton', APPLICATION = 'Application', SERVER = 'Server', REQUEST = 'Request',}
Scope for binding values
member APPLICATION
APPLICATION = 'Application'
Application scope
Remarks
The binding provides an application-scoped value within the context hierarchy. Resolved value for this binding will be cached and shared for the same application context (denoted by its scope property set to
BindingScope.APPLICATION
).
member CONTEXT
CONTEXT = 'Context'
Deprecated
Finer-grained scopes such as
APPLICATION
,SERVER
, orREQUEST
should be used instead to ensure the scope of sharing of resolved binding values.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 - req21.
0
is the resolved value for'b1'
within theapp
afterward - app.get('b1') ==> 0 (always)2.
'b1'
is resolved inapp
but not inreq1
, a new value1
is calculated and used forreq1
afterward - req1.get('b1') ==> 1 (always)3.
'b1'
is resolved inapp
but not inreq2
, a new value2
is calculated and used forreq2
afterward - req2.get('b1') ==> 2 (always)
member REQUEST
REQUEST = 'Request'
Request scope
Remarks
The binding provides an request-scoped value within the context hierarchy. Resolved value for this binding will be cached and shared for the same request context (denoted by its scope property set to
BindingScope.REQUEST
).The
REQUEST
scope is very useful for controllers, services and artifacts that want to have a single instance/value for a given request.
member SERVER
SERVER = 'Server'
Server scope
Remarks
The binding provides an server-scoped value within the context hierarchy. Resolved value for this binding will be cached and shared for the same server context (denoted by its scope property set to
BindingScope.SERVER
).It's possible that an application has more than one servers configured, such as a
RestServer
and aGrpcServer
. Both server contexts are created withscope
set toBindingScope.SERVER
. Depending on where a binding is resolved: - If the binding is resolved from the RestServer or below, it will be cached using the RestServer context as the key. - If the binding is resolved from the GrpcServer or below, it will be cached using the GrpcServer context as the key.The same binding can resolved/shared/cached for all servers, each of which has its own value for the binding.
member SINGLETON
SINGLETON = 'Singleton'
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 - req21.
0
is the singleton forapp
afterward - app.get('b1') ==> 0 (always)2.
'b1'
is resolved inapp
, reuse it forreq1
- req1.get('b1') ==> 0 (always)3.
'b1'
is resolved inapp
, reuse it forreq2
- req2.get('b1') ==> 0 (always)
member TRANSIENT
TRANSIENT = 'Transient'
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 - req2Now
'b1'
is resolved to a new value each time forapp
and its descendantsreq1
andreq2
: - app.get('b1') ==> 0 - req1.get('b1') ==> 1 - req2.get('b1') ==> 2 - req2.get('b1') ==> 3 - app.get('b1') ==> 4
enum BindingType
enum BindingType { CONSTANT = 'Constant', DYNAMIC_VALUE = 'DynamicValue', CLASS = 'Class', PROVIDER = 'Provider', ALIAS = 'Alias',}
Type of the binding source
member ALIAS
ALIAS = 'Alias'
A alias to another binding key with optional path
member CLASS
CLASS = 'Class'
A class to be instantiated as the value
member CONSTANT
CONSTANT = 'Constant'
A fixed value
member DYNAMIC_VALUE
DYNAMIC_VALUE = 'DynamicValue'
A function to get the value
member PROVIDER
PROVIDER = 'Provider'
A provider class with
value()
function to get the value
Type Aliases
type AliasBindingSource
type AliasBindingSource<T> = { type: BindingType.ALIAS; value: BindingAddress<T>;};
Binding source for
toAlias
type AsInterceptedFunction
type AsInterceptedFunction<T> = T extends (...args: InvocationArgs) => infer R ? (...args: Parameters<T>) => AsValueOrPromise<R> : T;
The intercepted variant of a function to return
ValueOrPromise<T>
. IfT
is not a function, the type isT
.
type AsValueOrPromise
type AsValueOrPromise<T> = T extends Promise<unknown> ? T : ValueOrPromise<T>;
Create the Promise type for
T
. IfT
extendsPromise
, the type isT
, otherwise the type isValueOrPromise<T>
.
type AsyncProxy
type AsyncProxy<T> = { [P in keyof T]: AsInterceptedFunction<T[P]>;};
The proxy type for
T
. The return type for any method ofT
with original return typeR
becomesValueOrPromise<R>
ifR
does not extendPromise
. Property types stay untouched.Example 1
class MyController {name: string;greet(name: string): string {return `Hello, ${name}`;}async hello(name: string) {return `Hello, ${name}`;}}AsyncProxy<MyController>
will be:{name: string; // the same as MyControllergreet(name: string): ValueOrPromise<string>; // the return type becomes `ValueOrPromise<string>`hello(name: string): Promise<string>; // the same as MyController}
type BindingAddress
type BindingAddress<T = unknown> = string | BindingKey<T>;
type BindingEvent
type BindingEvent = { /** * Event type */ type: 'changed' | string; /** * Source binding that emits the event */ binding: Readonly<Binding<unknown>>; /** * Operation that triggers the event */ operation: 'tag' | 'scope' | 'value' | string;};
Information for a binding event
type BindingEventListener
type BindingEventListener = ( /** * Binding event */ event: BindingEvent) => void;
Event listeners for binding events
type BindingFromClassOptions
type BindingFromClassOptions = { /** * Binding key */ key?: BindingAddress; /** * Artifact type, such as `server`, `controller`, `repository` or `service` */ type?: string; /** * Artifact name, such as `my-rest-server` and `my-controller`. It * overrides the name tag */ name?: string; /** * Namespace for the binding key, such as `servers` and `controllers`. It * overrides the default namespace or namespace tag */ namespace?: string; /** * Mapping artifact type to binding key namespaces */ typeNamespaceMapping?: TypeNamespaceMapping; /** * Default namespace if the binding does not have an explicit namespace */ defaultNamespace?: string; /** * Default scope if the binding does not have an explicit scope */ defaultScope?: BindingScope;};
Options to customize the binding created from a class
type BindingMetadata
type BindingMetadata<T = unknown> = { /** * An array of template functions to configure a binding */ templates: BindingTemplate<T>[]; /** * The target class where binding metadata is decorated */ target: Constructor<T>;};
Binding metadata from
@injectable
type BindingScopeAndTags
type BindingScopeAndTags = { scope?: BindingScope; tags?: BindingTag | BindingTag[];};
An object to configure binding scope and tags
type BindingSelector
type BindingSelector<ValueType = unknown> = | BindingAddress<ValueType> | BindingFilter;
Select binding(s) by key or a filter function
type BindingSource
type BindingSource<T> = | ConstantBindingSource<T> | DynamicValueBindingSource<T> | ClassBindingSource<T> | ProviderBindingSource<T> | AliasBindingSource<T>;
Source for the binding, including the type and value
type BindingSpec
type BindingSpec<T = unknown> = BindingTemplate<T> | BindingScopeAndTags;
Specification of parameters for
@injectable()
type BindingTag
type BindingTag = TagMap | string;
Binding tag can be a simple name or name/value pairs
type BindingTemplate
type BindingTemplate<T = unknown> = (binding: Binding<T>) => void;
A function as the template to configure bindings
type BoundValue
type BoundValue = any;
type ClassBindingSource
type ClassBindingSource<T> = { type: BindingType.CLASS; value: Constructor<T>;};
Binding source for
toClass
type ConstantBindingSource
type ConstantBindingSource<T> = { type: BindingType.CONSTANT; value: T;};
Binding source for
to
type Constructor
type Constructor<T> = new (...args: any[]) => T;
A class constructor accepting arbitrary arguments.
type ContextEvent
type ContextEvent = { /** * Source context that emits the event */ context: Context; /** * Binding that is being added/removed/updated */ binding: Readonly<Binding<unknown>>; /** * Event type */ type: string;};
Events emitted by a context
type ContextEventListener
type ContextEventListener = (event: ContextEvent) => void;
Synchronous listener for context events
type ContextEventObserver
type ContextEventObserver = ContextObserver | ContextObserverFn;
Context event observer type - An instance of
ContextObserver
or a function
type ContextEventType
type ContextEventType = 'bind' | 'unbind' | string;
Context event types. We support
bind
andunbind
for now but keep it open for new types
type ContextObserverFn
type ContextObserverFn = ( eventType: ContextEventType, binding: Readonly<Binding<unknown>>, context: Context) => ValueOrPromise<void>;
Listen on
bind
,unbind
, or other eventsParameter eventType
Context event type
Parameter binding
The binding as event source
Parameter context
Context object for the binding event
type DynamicValueBindingSource
type DynamicValueBindingSource<T> = { type: BindingType.DYNAMIC_VALUE; value: ValueFactory<T> | DynamicValueProviderClass<T>;};
Binding source for
toDynamicValue
type GenericInterceptor
type GenericInterceptor<C extends Context = Context> = ( context: C, next: Next) => ValueOrPromise<NonVoid>;
An interceptor function to be invoked in a chain for the given context. It serves as the base interface for various types of interceptors, such as method invocation interceptor or request/response processing interceptor.
Parameter context
Context object
Parameter next
A function to proceed with downstream interceptors or the target operation
Returns
The invocation result as a value (sync) or promise (async).
Remarks
We choose
NonVoid
as the return type to avoid possible bugs that an interceptor forgets to return the value fromnext()
. For example, the code below will fail to compile.const myInterceptor: Interceptor = async (ctx, next) {// preprocessing// ...// There is a subtle bug that the result from `next()` is not further// returned back to the upstream interceptorsconst result = await next();// postprocessing// ...// We must have `return ...` here// either return `result` or another value if the interceptor decides to// have its own response}
type GenericInterceptorOrKey
type GenericInterceptorOrKey<C extends Context = Context> = | BindingAddress<GenericInterceptor<C>> | GenericInterceptor<C>;
Interceptor function or a binding key that resolves a generic interceptor function
type Getter
type Getter<T> = () => Promise<T>;
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 thebindingSelector
is aBindingFilter
function.
type InterceptorOrKey
type InterceptorOrKey = GenericInterceptorOrKey<InvocationContext>;
Interceptor function or binding key that can be used as parameters for
@intercept()
type InvocationArgs
type InvocationArgs = any[];
Array of arguments for a method invocation
type InvocationOptions
type InvocationOptions = { /** * Skip dependency injection on method parameters */ skipParameterInjection?: boolean; /** * Skip invocation of interceptors */ skipInterceptors?: boolean; /** * Information about the source object that makes the invocation. For REST, * it's a `Route`. For injected proxies, it's a `Binding`. */ source?: InvocationSource; /** * Resolution session */ session?: ResolutionSession;};
Options to control invocations
type InvocationResult
type InvocationResult = any;
Return value for a method invocation
type JSONPrimitive
type JSONPrimitive = string | number | boolean | null;
JSON primitive types: - string - number - boolean - null
type JSONValue
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
JSON values - primitive - object - array
type MapObject
type MapObject<T> = Record<string, T>;
type Next
type Next = () => ValueOrPromise<NonVoid>;
The
next
function that can be used to invoke next generic interceptor in the chain
type NonVoid
type NonVoid = string | number | boolean | null | undefined | object;
Any type except
void
. We use this type to enforce that interceptor functions always return a value (including undefined or null).
type ProviderBindingSource
type ProviderBindingSource<T> = { type: BindingType.PROVIDER; value: Constructor<Provider<T>>;};
Binding source for
toProvider
type ResolutionAction
type ResolutionAction = (session: ResolutionSession) => ValueOrPromise<BoundValue>;
A function to be executed with the resolution session
type ResolutionElement
type ResolutionElement = BindingElement | InjectionElement;
Binding or injection elements tracked by resolution sessions
type ResolutionOptionsOrSession
type ResolutionOptionsOrSession = ResolutionOptions | ResolutionSession;
Resolution options or session
type Setter
type Setter<T> = (value: T) => void;
The function injected by
@inject.setter(bindingKey)
. It sets the underlying binding to a constant value usingbinding.to(value)
.Parameter value
The value for the underlying binding
Example 1
setterFn('my-value');
type TagMap
type TagMap = MapObject<any>;
type TypeNamespaceMapping
type TypeNamespaceMapping = { [name: string]: string;};
Mapping artifact types to binding key namespaces (prefixes).
Example 1
{repository: 'repositories'}
type ValueFactory
type ValueFactory<T = unknown> = ( resolutionCtx: ResolutionContext) => ValueOrPromise<T | undefined>;
A factory function for
toDynamicValue
type ValueOrPromise
type ValueOrPromise<T> = T | PromiseLike<T>;
Representing a value or promise. This type is used to represent results of synchronous/asynchronous resolution of values.
Note that we are using PromiseLike instead of native Promise to describe the asynchronous variant. This allows producers of async values to use any Promise implementation (e.g. Bluebird) instead of native Promises provided by JavaScript runtime.
Namespaces
namespace bind
namespace bind {}
Alias namespace
bind
toinjectable
for backward compatibilityIt should have the same members as
bind
.
variable provider
const provider: ( ...specs: BindingSpec<unknown>[]) => (target: Constructor<unknown>) => void;
See documentation for injectable.provider.
namespace config
namespace config {}
function getter
getter: ( propertyPath?: string | ConfigInjectionMetadata, metadata?: ConfigInjectionMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
@inject.getter
decorator to inject a config getter functionParameter propertyPath
Optional property path of the config object
Parameter metadata
Injection metadata
function view
view: ( propertyPath?: string | ConfigInjectionMetadata, metadata?: ConfigInjectionMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
@inject.view
decorator to inject a config context view to allow dynamic changes in configurationParameter propertyPath
Optional property path of the config object
Parameter metadata
Injection metadata
namespace ContextBindings
namespace ContextBindings {}
Namespace for context bindings
variable CONFIGURATION_RESOLVER
const CONFIGURATION_RESOLVER: BindingKey<ConfigurationResolver>;
Binding key for ConfigurationResolver
variable GLOBAL_INTERCEPTOR_ORDERED_GROUPS
const GLOBAL_INTERCEPTOR_ORDERED_GROUPS: BindingKey<string[]>;
Binding key for ordered groups of global interceptors
namespace ContextTags
namespace ContextTags {}
Namespace for context tags
variable CLASS
const CLASS: string;
variable CONFIGURATION_FOR
const CONFIGURATION_FOR: string;
Binding tag to associate a configuration binding with the target binding key
variable DYNAMIC_VALUE_PROVIDER
const DYNAMIC_VALUE_PROVIDER: string;
variable GLOBAL_INTERCEPTOR
const GLOBAL_INTERCEPTOR: string;
Binding tag for global interceptors
variable GLOBAL_INTERCEPTOR_GROUP
const GLOBAL_INTERCEPTOR_GROUP: string;
Binding tag for group name of global interceptors
variable GLOBAL_INTERCEPTOR_SOURCE
const GLOBAL_INTERCEPTOR_SOURCE: string;
Binding tag for global interceptors to specify sources of invocations that the interceptor should apply. The tag value can be a string or string[], such as
'route'
or['route', 'proxy']
.
variable KEY
const KEY: string;
Binding key for the artifact
variable NAME
const NAME: string;
Name of the artifact
variable NAMESPACE
const NAMESPACE: string;
Namespace of the artifact
variable PROVIDER
const PROVIDER: string;
variable TYPE
const TYPE: string;
Type of the artifact
namespace Getter
namespace Getter {}
function fromValue
fromValue: <T>(value: T) => Getter<T>;
Convert a value into a Getter returning that value.
Parameter value
namespace inject
namespace inject {}
function binding
binding: ( bindingKey?: string | BindingKey<unknown>, metadata?: InjectBindingMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
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 themetadata.bindingCreation
option. SeeBindingCreationPolicy
for more details.Parameter bindingKey
Binding key
Parameter metadata
Metadata for the injection
Example 1
class MyAuthAction {@inject.binding('current-user', {bindingCreation: BindingCreationPolicy.ALWAYS_CREATE,})private userBinding: Binding<UserProfile>;async authenticate() {this.userBinding.toDynamicValue(() => {...});}}
function context
context: () => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
Inject the context object.
Example 1
class MyProvider {constructor(@inject.context() private ctx: Context) {}}
function getter
getter: ( bindingSelector: BindingSelector<unknown>, metadata?: InjectionMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
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>
.Parameter bindingSelector
The binding key or filter we want to eventually get value(s) from.
Parameter metadata
Optional metadata to help the injection
function setter
setter: ( bindingKey: BindingAddress, metadata?: InjectBindingMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
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>
.Parameter bindingKey
The key of the value we want to set.
Parameter metadata
Optional metadata to help the injection
function tag
tag: ( bindingTag: BindingTag | RegExp, metadata?: InjectionMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
Inject an array of values by a tag pattern string or regexp
Parameter bindingTag
Tag name, regex or object
Parameter metadata
Optional metadata to help the injection
Example 1
class AuthenticationManager {constructor(@inject.tag('authentication.strategy') public strategies: Strategy[],) {}}
function view
view: ( bindingFilter: BindingFilter, metadata?: InjectionMetadata) => ( target: Object, member: string | undefined, methodDescriptorOrParameterIndex?: | number | TypedPropertyDescriptor<any> | undefined) => void;
Inject matching bound values by the filter function
Parameter bindingFilter
A binding filter function
Parameter metadata
Example 1
class MyControllerWithView {@inject.view(filterByTag('foo'))view: ContextView<string[]>;}
namespace injectable
namespace injectable {}
A namespace to host shortcuts for
@injectable
function provider
provider: (...specs: BindingSpec[]) => (target: Constructor<unknown>) => void;
@injectable.provider
to denote a provider classA list of binding scope/tags or template functions to configure the binding
Package Files (25)
- dist/binding-config.d.ts
- dist/binding-decorator.d.ts
- dist/binding-filter.d.ts
- dist/binding-inspector.d.ts
- dist/binding-key.d.ts
- dist/binding-sorter.d.ts
- dist/binding.d.ts
- dist/context-event.d.ts
- dist/context-observer.d.ts
- dist/context-subscription.d.ts
- dist/context-view.d.ts
- dist/context.d.ts
- dist/index.d.ts
- dist/inject-config.d.ts
- dist/inject.d.ts
- dist/interception-proxy.d.ts
- dist/interceptor-chain.d.ts
- dist/interceptor.d.ts
- dist/invocation.d.ts
- dist/json-types.d.ts
- dist/keys.d.ts
- dist/provider.d.ts
- dist/resolution-session.d.ts
- dist/resolver.d.ts
- dist/value-promise.d.ts
Dependencies (7)
Dev Dependencies (7)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@loopback/context
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@loopback/context)
- HTML<a href="https://www.jsdocs.io/package/@loopback/context"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5941 ms. - Missing or incorrect documentation? Open an issue for this package.