Page Contents

Home > @loopback/context

context package

@loopback/context

Classes

Class Description
Binding Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.
BindingKey  
Context Context provides an implementation of Inversion of Control (IoC) container
ContextSubscriptionManager Manager for context observer subscriptions
ContextView ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.ContextView is an event emitter that emits the following events: - ‘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
DefaultConfigurationResolver Resolver for configurations of bindings
GenericInterceptorChain A chain of generic interceptors to be invoked for the given context
InterceptedInvocationContext A specialized InvocationContext for interceptors
InterceptionHandler A proxy handler that applies interceptorsSee https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
InvocationContext InvocationContext represents the context to invoke interceptors for a method. The context can be used to access metadata about the invocation as well as other dependencies.
ProxySource Invocation source for injected proxies. It wraps a snapshot of the ResolutionSession that tracks the binding/injection stack.
ResolutionError Error for context binding resolutions and dependency injections
ResolutionSession Object to keep states for a session to resolve bindings and their dependencies within a context

Enumerations

Enumeration Description
BindingCreationPolicy Policy to control if a binding should be created for the context
BindingScope Scope for binding values
BindingType Type of the binding source

Functions

Function Description
asBindingTemplate(scopeAndTags) Convert binding scope and tags as a template function
asClassOrProvider(target) A factory function to create a template function to bind the target class as a class or Provider.
asGlobalInterceptor(group) The BindingTemplate function to configure a binding as a global interceptor by tagging it with ContextTags.INTERCEPTOR
asProvider(target) A factory function to create a template function to bind the target class as a Provider.
asResolutionOptions(optionsOrSession) Normalize ResolutionOptionsOrSession to ResolutionOptions
assertTargetType(injection, expectedType, expectedTypeName) Assert the target type inspected from TypeScript for injection to be the expected type. If the types don’t match, an error is thrown.
bind(specs) Decorate a class with binding configuration
bindingTemplateFor(cls) Get the binding template for a class with binding metadata
compareBindingsByTag(phaseTagName, orderOfPhases) Creates a binding compare function to sort bindings by tagged phase name.
compareByOrder(a, b, order) Compare two values by the predefined order
composeInterceptors(interceptors) Compose a list of interceptors as a single interceptor
config(propertyPath, metadata) 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 with optional: true by default.
configBindingKeyFor(key, propertyPath) Create binding key for configuration of the binding
createBindingFromClass(cls, options) Create a binding from a class with decorated metadata. The class is attached to the binding as follows: - binding.toClass(cls): if cls is a plain class such as MyController - binding.toProvider(cls): it cls is a value provider class with a prototype method value()
createProxyWithInterceptors(target, context, session, source) Create a proxy that applies interceptors for method invocations
createViewGetter(ctx, bindingFilter, session) Create a context view as a getter with the given filter
createViewGetter(ctx, bindingFilter, bindingComparator, session) Create a context view as a getter with the given filter and sort matched bindings by the comparator.
describeInjectedArguments(target, method) Return an array of injection objects for parameters
describeInjectedProperties(target) Return a map of injection objects for properties
filterByKey(keyPattern) Create a binding filter from key pattern
filterByTag(tagPattern) Create a binding filter for the tag pattern
getBindingMetadata(target) Get binding metadata for a class
getDeepProperty(value, path) Get nested properties of an object by path
globalInterceptor(group, specs) @globalInterceptor decorator to mark the class as a global interceptor
includesTagValue(itemValues) 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.
inject(bindingSelector, metadata, resolve) A decorator to annotate method arguments for automatic injection by LoopBack IoC container.
inspectInjections(binding) Inspect injections for a binding created with toClass or toProvider
inspectTargetType(injection) Inspect the target type for the injection to find out the corresponding JavaScript type
instantiateClass(ctor, ctx, session, nonInjectedArgs) 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.
intercept(interceptorOrKeys) Decorator function @intercept for classes/methods to apply interceptors. It can be applied on a class and its public methods. Multiple occurrences of @intercept are allowed on the same target class or method. The decorator takes a list of interceptor functions or binding keys.
invokeInterceptors(context, interceptors) Invoke a chain of interceptors with the context
invokeMethod(target, method, ctx, nonInjectedArgs, options) Invoke a method using dependency injection. Interceptors are invoked as part of the invocation.
invokeMethodWithInterceptors(context, target, methodName, args, options) Invoke a method with the given context
isBindingAddress(bindingSelector) Type guard for binding address
isBindingTagFilter(filter) Type guard for BindingTagFilter
isDynamicValueProviderClass(factory) Check if the factory is a value factory provider class
isPromiseLike(value) Check whether a value is a Promise-like instance. Recognizes both native promises and third-party promise libraries.
isProviderClass(cls) Check if a class implements Provider interface
mergeInterceptors(interceptorsFromSpec, existingInterceptors) 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]
registerInterceptor(ctx, interceptor, options) Register an interceptor function or provider class to the given context
removeNameAndKeyTags(binding) A binding template function to delete name and key tags
resolveInjectedArguments(target, method, ctx, session, nonInjectedArgs) Given a function with arguments decorated with @inject, return the list of arguments resolved using the values bound in ctx.The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.
resolveInjectedProperties(constructor, ctx, session) Given a class with properties decorated with @inject, return the map of properties resolved using the values bound in ctx.The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.
resolveList(list, resolver) 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.
resolveMap(map, resolver) 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.
resolveUntil(source, resolver, evaluator) Resolve an iterator of source values into a result until the evaluator returns true
sortBindingsByPhase(bindings, phaseTagName, orderOfPhases) Sort bindings by phase names denoted by a tag and the predefined order
transformValueOrPromise(valueOrPromise, transformer) Transform a value or promise with a function that produces a new value or promise
tryCatchFinally(action, errorAction, finalAction) 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.
tryWithFinally(action, finalAction) Try to run an action that returns a promise or a value
uuid() A utility to generate uuid v4

Interfaces

Interface Description
BindingComparator Compare function to sort an array of bindings. It is used by Array.prototype.sort().
BindingElement Wrapper for bindings tracked by resolution sessions
BindingFilter A function that filters bindings. It returns true to select a given binding.
BindingInspectOptions Options for binding.inspect()
BindingTagFilter Binding filter function that holds a binding tag pattern. Context.find() uses the bindingTagPattern to optimize the matching of bindings by tag to avoid expensive check for all bindings.
ConfigInjectionMetadata Injection metadata for @config.*
ConfigurationResolver Resolver for configuration of bindings. It’s responsible for finding corresponding configuration for a given binding key.By default, undefined is expected if no configuration is provided. The behavior can be overridden by setting optional to false in resolution options.
ContextInspectOptions Options for context.inspect()
ContextObserver Observers of context bind/unbind events
ContextViewEvent An event emitted by a ContextView
DynamicValueProviderClass A class with a static value method as the factory function for toDynamicValue.
InjectBindingMetadata Metadata for @inject.binding
Injection Descriptor for an injection point
InjectionDescriptor  
InjectionElement Wrapper for injections tracked by resolution sessions
InjectionMetadata An object to provide metadata for @inject
Interceptor Interceptor function to intercept method invocations
InterceptorBindingOptions Options for an interceptor binding
InvocationSource An interface to represent the caller of the invocation
JSONArray JSON array
JSONObject JSON object
Notification Event data for observer notifications
Provider Providers allow developers to compute injected values dynamically, with any dependencies required by the value getter injected automatically from the Context.
ResolutionContext Contextual metadata for resolution
ResolutionOptions Options for binding/dependency resolution
ResolverFunction A function to provide resolution of injected values.
Subscription Subscription of context events. It’s modeled after https://github.com/tc39/proposal-observable.
TagValueMatcher A function to check if a given tag value is matched for filterByTag

Namespaces

Namespace Description
bind  
config  
ContextBindings Namespace for context bindings
ContextTags Namespace for context tags
Getter  
inject  

Variables

Variable Description
ANY_TAG_VALUE A symbol that can be used to match binding tags by name regardless of the value.
BINDING_METADATA_KEY Metadata key for binding metadata
DEFAULT_TYPE_NAMESPACES  
GLOBAL_INTERCEPTOR_NAMESPACE Default namespace for global interceptors
INTERCEPT_CLASS_KEY Metadata key for method-level interceptors
INTERCEPT_METHOD_KEY Metadata key for method-level interceptors
LOCAL_INTERCEPTOR_NAMESPACE Default namespace for local interceptors
UUID_PATTERN A regular expression for testing uuid v4 PATTERN

Type Aliases

| Type Alias | Description | | — | — | | AliasBindingSource | Binding source for toAlias | | AsInterceptedFunction | The intercepted variant of a function to return ValueOrPromise<T>. If T is not a function, the type is T. | | AsValueOrPromise | Create the Promise type for T. If T extends Promise, the type is T, otherwise the type is ValueOrPromise<T>. | | AsyncProxy | The proxy type for T. The return type for any method of T with original return type R becomes ValueOrPromise<R> if R does not extend Promise. Property types stay untouched. | | BindingAddress | | | BindingEvent | Information for a binding event | | BindingEventListener | Event listeners for binding events | | BindingFromClassOptions | Options to customize the binding created from a class | | BindingMetadata | Binding metadata from @bind | | BindingScopeAndTags | An object to configure binding scope and tags | | BindingSelector | Select binding(s) by key or a filter function | | BindingSource | Source for the binding, including the type and value | | BindingSpec | Specification of parameters for @bind() | | BindingTag | Binding tag can be a simple name or name/value pairs | | BindingTemplate | A function as the template to configure bindings | | BoundValue | | | ClassBindingSource | Binding source for toClass | | ConstantBindingSource | Binding source for to | | Constructor | A class constructor accepting arbitrary arguments. | | ContextEvent | Events emitted by a context | | ContextEventListener | Synchronous listener for context events | | ContextEventObserver | Context event observer type - An instance of ContextObserver or a function | | ContextEventType | Context event types. We support bind and unbind for now but keep it open for new types | | ContextObserverFn | Listen on bind, unbind, or other events | | DynamicValueBindingSource | Binding source for toDynamicValue | | GenericInterceptor | 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.We choose NonVoid as the return type to avoid possible bugs that an interceptor forgets to return the value from next(). 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 interceptors
  const result = await next();

  // postprocessing
  // ...
  // We must have `return ...` here
  // either return `result` or another value if the interceptor decides to
  // have its own response
}

| | GenericInterceptorOrKey | Interceptor function or a binding key that resolves a generic interceptor function | | Getter | The function injected by @inject.getter(bindingSelector). It can be used to fetch bound value(s) from the underlying binding(s). The return value will be an array if the bindingSelector is a BindingFilter function. | | InterceptorOrKey | Interceptor function or binding key that can be used as parameters for @intercept() | | InvocationArgs | Array of arguments for a method invocation | | InvocationOptions | Options to control invocations | | InvocationResult | Return value for a method invocation | | JSONPrimitive | JSON primitive types: - string - number - boolean - null | | JSONValue | JSON values - primitive - object - array | | MapObject | | | Next | The next function that can be used to invoke next generic interceptor in the chain | | NonVoid | Any type except void. We use this type to enforce that interceptor functions always return a value (including undefined or null). | | ProviderBindingSource | Binding source for toProvider | | ResolutionAction | A function to be executed with the resolution session | | ResolutionElement | Binding or injection elements tracked by resolution sessions | | ResolutionOptionsOrSession | Resolution options or session | | Setter | The function injected by @inject.setter(bindingKey). It sets the underlying binding to a constant value using binding.to(value). | | TagMap | | | TypeNamespaceMapping | Mapping artifact types to binding key namespaces (prefixes). | | ValueFactory | A factory function for toDynamicValue | | ValueOrPromise | 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. |