awilix

  • Version 5.0.1
  • Published
  • 299 kB
  • 2 dependencies
  • MIT license

Install

npm i awilix
yarn add awilix
pnpm add awilix

Overview

Extremely powerful dependency injection container.

Index

Variables

variable InjectionMode

const InjectionMode: Record<InjectionModeType, InjectionModeType>;
  • Resolution modes.

variable Lifetime

const Lifetime: Record<LifetimeType, LifetimeType>;
  • Lifetime types.

variable RESOLVER

const RESOLVER: Symbol;
  • RESOLVER symbol can be used by modules loaded by loadModules to configure their lifetime, injection mode, etc.

Functions

function aliasTo

aliasTo: <T>(name: string) => Resolver<T>;
  • Resolves to the specified registration.

function asClass

asClass: <T = {}>(
Type: Constructor<T>,
opts?: BuildResolverOptions<T>
) => BuildResolver<T> & DisposableResolver<T>;
  • Like a factory resolver, but for classes that require new.

    Parameter name

    The name to register the value as.

    Parameter Type

    The function to register.

    Parameter opts

    Additional options for the resolver.

    {object} The resolver.

function asFunction

asFunction: <T>(
fn: FunctionReturning<T>,
opts?: BuildResolverOptions<T>
) => BuildResolver<T> & DisposableResolver<T>;
  • Creates a factory resolver, where the given factory function will be invoked with new when requested.

    Parameter name

    The name to register the value as.

    Parameter fn

    The function to register.

    Parameter opts

    Additional options for the resolver.

    {object} The resolver.

function asValue

asValue: <T>(value: T) => Resolver<T>;
  • Creates a simple value resolver where the given value will always be resolved.

    Parameter name

    The name to register the value as.

    Parameter value

    The value to resolve.

    {object} The resolver.

function createBuildResolver

createBuildResolver: <T, B extends Resolver<T>>(obj: B) => BuildResolver<T> & B;
  • Given an options object, creates a fluid interface to manage it.

    Parameter obj

    The object to return.

    {object} The interface.

function createContainer

createContainer: <T extends object = any, U extends object = any>(
options?: ContainerOptions,
parentContainer?: AwilixContainer<U>
) => AwilixContainer<T>;
  • Creates an Awilix container instance.

    Parameter

    {Function} options.require The require function to use. Defaults to require.

    Parameter

    {string} options.injectionMode The mode used by the container to resolve dependencies. Defaults to 'Proxy'.

    {object} The container.

function createDisposableResolver

createDisposableResolver: <T, B extends Resolver<T>>(
obj: B
) => DisposableResolver<T> & B;
  • Given a resolver, returns an object with methods to manage the disposer function.

    Parameter obj

function listModules

listModules: (
globPatterns: string | Array<string | GlobWithOptions>,
opts?: ListModulesOptions
) => ModuleDescriptor[];
  • Returns a list of {name, path} pairs, where the name is the module name, and path is the actual full path to the module.

    Parameter globPatterns

    The glob pattern as a string or an array of strings.

    Parameter

    {String} opts.cwd Current working directory, used for resolving filepaths. Defaults to process.cwd().

    {[{name, path}]} An array of objects with the module names and paths.

Classes

class AwilixError

class AwilixError extends ExtendableError {}
  • Base error for all Awilix-specific errors.

class AwilixResolutionError

class AwilixResolutionError extends AwilixError {}
  • A nice error class so we can do an instanceOf check.

constructor

constructor(
name: string | symbol,
resolutionStack: ResolutionStack,
message?: string
);
  • Constructor, takes the registered modules and unresolved tokens to create a message.

    Parameter name

    The name of the module that could not be resolved.

    Parameter resolutionStack

    The current resolution stack

class AwilixTypeError

class AwilixTypeError extends AwilixError {}
  • Error thrown to indicate a type mismatch. TODO(v3): remove AwilixNotAFunctionError and use this.

constructor

constructor(
funcDescription: string,
paramName: string,
expectedType: string,
givenType: any
);
  • Constructor, takes the function name, expected and given type to produce an error.

    Parameter funcDescription

    Name of the function being guarded.

    Parameter paramName

    The parameter there was an issue with.

    Parameter expectedType

    Name of the expected type.

    Parameter givenType

    Name of the given type.

method assert

static assert: <T>(
condition: T,
funcDescription: string,
paramName: string,
expectedType: string,
givenType: any
) => T;
  • Asserts the given condition, throws an error otherwise.

    Parameter condition

    The condition to check

    Parameter funcDescription

    Name of the function being guarded.

    Parameter paramName

    The parameter there was an issue with.

    Parameter expectedType

    Name of the expected type.

    Parameter givenType

    Name of the given type.

class ExtendableError

class ExtendableError extends Error {}
  • An extendable error class. https://github.com/bjyoungblood/es6-error/

constructor

constructor(message: string);
  • Constructor for the error.

    Parameter message

    The error message.

Interfaces

interface AwilixContainer

interface AwilixContainer<Cradle extends object = any> {}
  • The container returned from createContainer has some methods and properties. AwilixContainer

property cache

readonly cache: Map<string | symbol, CacheEntry>;
  • Resolved modules cache.

property cradle

readonly cradle: Cradle;
  • The proxy injected when using PROXY injection mode. Can be used as-is.

property options

options: ContainerOptions;
  • Options the container was configured with.

property registrations

readonly registrations: RegistrationHash;
  • Getter for the rolled up registrations that merges the container family tree.

method build

build: <T>(
targetOrResolver: ClassOrFunctionReturning<T> | Resolver<T>,
opts?: BuildResolverOptions<T>
) => T;
  • Given a resolver, class or function, builds it up and returns it. Does not cache it, this means that any lifetime configured in case of passing a resolver will not be used.

    Parameter targetOrResolver

    Parameter opts

method createScope

createScope: <T extends object = {}>() => AwilixContainer<Cradle & T>;
  • Creates a scoped container with this one as the parent.

method dispose

dispose: () => Promise<void>;
  • Disposes this container and it's children, calling the disposer on all disposable registrations and clearing the cache. Only applies to registrations with SCOPED or SINGLETON lifetime.

method has

has: (name: string | symbol) => boolean;
  • Checks if the registration with the given name exists.

    Parameter name

    The name of the registration to resolve.

    {boolean} Whether or not the registration exists.

method inspect

inspect: (depth: number, opts?: any) => string;
  • Used by util.inspect.

method loadModules

loadModules: <ESM extends boolean = false>(
globPatterns: Array<string | GlobWithOptions>,
options?: LoadModulesOptions<ESM>
) => ESM extends false ? this : Promise<this>;
  • Binds lib/loadModules to this container, and provides real implementations of it's dependencies.

    Additionally, any modules using the dependsOn API will be resolved.

    See Also

    • src/load-modules.ts documentation.

method register

register: {
<T>(name: string | symbol, registration: Resolver<T>): this;
(nameAndRegistrationPair: NameAndRegistrationPair<Cradle>): this;
};
  • Adds a single registration that using a pre-constructed resolver.

  • Pairs resolvers to registration names and registers them.

method resolve

resolve: {
<K extends keyof Cradle>(
name: K,
resolveOptions?: ResolveOptions
): Cradle[K];
<T>(name: string | symbol, resolveOptions?: ResolveOptions): T;
};
  • Resolves the registration with the given name.

    Parameter name

    The name of the registration to resolve.

    {*} Whatever was resolved.

interface BuildResolver

interface BuildResolver<T> extends Resolver<T>, BuildResolverOptions<T> {}
  • A resolver object created by asClass() or asFunction().

property injectionMode

injectionMode?: InjectionModeType;

    property injector

    injector?: InjectorFunction;

      method classic

      classic: () => this;

        method inject

        inject: (injector: InjectorFunction) => this;

          method proxy

          proxy: () => this;

            method scoped

            scoped: () => this;

              method setInjectionMode

              setInjectionMode: (mode: InjectionModeType) => this;

                method setLifetime

                setLifetime: (lifetime: LifetimeType) => this;

                  method singleton

                  singleton: () => this;

                    method transient

                    transient: () => this;

                      interface BuildResolverOptions

                      interface BuildResolverOptions<T>
                      extends ResolverOptions<T>,
                      DisposableResolverOptions<T> {}
                      • Builder resolver options.

                      property injectionMode

                      injectionMode?: InjectionModeType;
                      • Resolution mode.

                      property injector

                      injector?: InjectorFunction;
                      • Injector function to provide additional parameters.

                      interface CacheEntry

                      interface CacheEntry<T = any> {}
                      • Cache entry.

                      property resolver

                      resolver: Resolver<T>;
                      • The resolver that resolved the value.

                      property value

                      value: T;
                      • The resolved value.

                      interface ContainerOptions

                      interface ContainerOptions {}
                      • The options for the createContainer function. ContainerOptions

                      property injectionMode

                      injectionMode?: InjectionModeType;

                        property require

                        require?: (id: string) => any;

                          interface DisposableResolver

                          interface DisposableResolver<T> extends Resolver<T>, DisposableResolverOptions<T> {}
                          • Disposable resolver.

                          method disposer

                          disposer: (dispose: Disposer<T>) => this;

                            interface DisposableResolverOptions

                            interface DisposableResolverOptions<T> extends ResolverOptions<T> {}
                            • Options for disposable resolvers.

                            property dispose

                            dispose?: Disposer<T>;

                              interface ListModulesOptions

                              interface ListModulesOptions {}
                              • The options when invoking listModules(). ListModulesOptions

                              property cwd

                              cwd?: string;

                                property glob

                                glob?: typeof glob.sync;

                                  interface LoadedModuleDescriptor

                                  interface LoadedModuleDescriptor extends ModuleDescriptor {}
                                  • Metadata of the module as well as the loaded module itself.

                                  property value

                                  value: unknown;

                                    interface ModuleDescriptor

                                    interface ModuleDescriptor {}
                                    • An object containing the module name and path (full path to module).

                                      ModuleDescriptor

                                    property name

                                    name: string;

                                      property opts

                                      opts: any;

                                        property path

                                        path: string;

                                          interface ResolutionStack

                                          interface ResolutionStack extends Array<string | symbol> {}
                                          • Resolution stack.

                                          interface ResolveOptions

                                          interface ResolveOptions {}
                                          • Optional resolve options.

                                          property allowUnregistered

                                          allowUnregistered?: boolean;
                                          • If true and resolve cannot find the requested dependency, returns undefined rather than throwing an error.

                                          interface Resolver

                                          interface Resolver<T> extends ResolverOptions<T> {}
                                          • A resolver object returned by asClass(), asFunction() or asValue().

                                          method resolve

                                          resolve: <U extends object>(container: AwilixContainer<U>) => T;

                                            interface ResolverOptions

                                            interface ResolverOptions<T> {}
                                            • The options when registering a class, function or value. RegistrationOptions

                                            property lifetime

                                            lifetime?: LifetimeType;
                                            • Lifetime setting.

                                            property name

                                            name?: string;
                                            • Only used for inline configuration with loadModules.

                                            property register

                                            register?: (...args: any[]) => Resolver<T>;
                                            • Registration function to use. Only used for inline configuration with loadModules.

                                            Type Aliases

                                            type ClassOrFunctionReturning

                                            type ClassOrFunctionReturning<T> = FunctionReturning<T> | Constructor<T>;
                                            • A class or function returning T.

                                            type Constructor

                                            type Constructor<T> = {
                                            new (...args: any[]): T;
                                            };
                                            • A class constructor. For example:

                                              class MyClass {}

                                              container.registerClass('myClass', MyClass) ^^^^^^^

                                            type Disposer

                                            type Disposer<T> = (value: T) => any | Promise<any>;
                                            • Disposer function type.

                                            type FunctionReturning

                                            type FunctionReturning<T> = (...args: Array<any>) => T;
                                            • Function that returns T.

                                            type GlobWithOptions

                                            type GlobWithOptions = [string] | [string, BuildResolverOptions<any> | LifetimeType];
                                            • A glob pattern with associated registration options.

                                            type InjectionModeType

                                            type InjectionModeType = 'PROXY' | 'CLASSIC';
                                            • Injection mode type.

                                            type InjectorFunction

                                            type InjectorFunction = <T extends object>(container: AwilixContainer<T>) => object;
                                            • Gets passed the container and is expected to return an object whose properties are accessible at construction time for the configured resolver.

                                              {Function}

                                            type LifetimeType

                                            type LifetimeType = 'SINGLETON' | 'TRANSIENT' | 'SCOPED';
                                            • Lifetime type.

                                            type NameAndRegistrationPair

                                            type NameAndRegistrationPair<T> = {
                                            [U in keyof T]?: Resolver<T[U]>;
                                            };
                                            • Register a Registration NameAndRegistrationPair

                                            type RegistrationHash

                                            type RegistrationHash = Record<string | symbol | number, Resolver<any>>;
                                            • Contains a hash of registrations where the name is the key.

                                            Package Files (7)

                                            Dependencies (2)

                                            Dev Dependencies (29)

                                            Peer Dependencies (0)

                                            No peer dependencies.

                                            Badge

                                            To add a badge like this onejsDocs.io badgeto 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/awilix.

                                            • Markdown
                                              [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/awilix)
                                            • HTML
                                              <a href="https://www.jsdocs.io/package/awilix"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>