npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@travetto/di

v5.0.13

Published

Dependency registration/management and injection support.

Downloads

504

Readme

Dependency Injection

Dependency registration/management and injection support.

Install: @travetto/di

npm install @travetto/di

# or

yarn add @travetto/di

Dependency injection is a framework primitive. When used in conjunction with automatic file scanning, it provides for handling of application dependency wiring. Due to the nature of Typescript and type erasure of interfaces, dependency injection only supports classes as a type signifier. The primary goal of dependency injection is to allow for separation of concerns of object creation and it's usage.

Declaration

The @Injectable and @InjectableFactory decorators provide the registration of dependencies. Dependency declaration revolves around exposing classes and subtypes thereof to provide necessary functionality. Additionally, the framework will utilize dependencies to satisfy contracts with various implementation.

Code: Example Injectable

import { Injectable } from '@travetto/di';

@Injectable()
class CustomService {
  async coolOperation() {
    // Do work!
  }
}

When declaring a dependency, you can also provide a token to allow for multiple instances of the dependency to be defined. This can be used in many situations:

Code: Example Injectable with multiple targets

import { Injectable, Inject } from '@travetto/di';

@Injectable()
class CustomService {
  async coolOperation() {
    // do work!
  }
}

const CUSTOM2 = Symbol.for('di-custom2');

@Injectable({ target: CustomService, qualifier: CUSTOM2 })
class CustomService2 extends CustomService {
  override async coolOperation() {
    await super.coolOperation();
    // Do some additional work
  }
}

class Consumer {
  @Inject(CUSTOM2) // Pull in specific service
  service: CustomService;
}

As you can see, the target field is also set, which indicates to the dependency registration process what class the injectable is compatible with. Additionally, when using abstract classes, the parent class is always considered as a valid candidate type.

Code: Example Injectable with target via abstract class

import { Injectable } from '@travetto/di';

abstract class BaseService {
  abstract work(): Promise<void>;
}

@Injectable()
class SpecificService extends BaseService {
  async work() {
    // Do some additional work
  }
}

In this scenario, SpecificService is a valid candidate for BaseService due to the abstract inheritance. Sometimes, you may want to provide a slight variation to a dependency without extending a class. To this end, the @InjectableFactory decorator denotes a static class method that produces an @Injectable.

Code: Example InjectableFactory

import { InjectableFactory } from '@travetto/di';

// Not injectable by default
class CoolService {

}

class Config {
  @InjectableFactory()
  static initService() {
    return new CoolService();
  }
}

Given the static method initService, the function will be provided as a valid candidate for CoolService. Instead of calling the constructor of the type directly, this function will work as a factory for producing the injectable.

Code: Example Conditional Dependency

import { Runtime } from '@travetto/runtime';
import { Inject, Injectable } from '@travetto/di';

@Injectable({ enabled: Runtime.production })
class ProductionLogger {
  async log() {
    console.log('This will only run in production');
  }
}

@Injectable()
class RuntimeService {
  @Inject()
  logger?: ProductionLogger;

  action(): void {
    // Only injected when available, in prod
    this.logger?.log();
    // Do work
  }
}

In this example, the enabled flag is specified in relationship to the deployment environment. When coupled with optional properties, and optional chaining, allows for seamless inclusion of optional dependencies at runtime.

Note: Other modules are able to provide aliases to @Injectable that also provide additional functionality. For example, the Configuration module @Config or the RESTful API module @Controller decorator registers the associated class as an injectable element.

Injection

Once all of your necessary dependencies are defined, now is the time to provide those @Injectable instances to your code. There are three primary methods for injection:

The @Inject decorator, which denotes a desire to inject a value directly. These will be set post construction.

Code: Example Injectable with dependencies as Inject fields

import { Injectable, Inject } from '@travetto/di';
import { DependentService } from './dep';

@Injectable()
class CustomService {
  @Inject()
  private dependentService: DependentService;

  async coolOperation() {
    await this.dependentService.doWork();
  }
}

The @Injectable constructor params, which will be provided as the instance is being constructed.

Code: Example Injectable with dependencies in constructor

import { Injectable } from '@travetto/di';
import { DependentService } from './dep';

@Injectable()
class CustomService {
  constructor(private dependentService: DependentService) { }

  async coolOperation() {
    await this.dependentService.doWork();
  }
}

Via @InjectableFactory params, which are comparable to constructor params

Code: Example InjectableFactory with parameters as dependencies

import { InjectableFactory } from '@travetto/di';

import { DependentService, CustomService } from './dep';

class Config {
  @InjectableFactory()
  static initService(dependentService: DependentService) {
    return new CustomService(dependentService);
  }
}

Multiple Candidates for the Same Type

If you are building modules for others to consume, often times it is possible to end up with multiple implementations for the same class.

Code: Example Multiple Candidate Types

import { Injectable, Inject } from '@travetto/di';

export abstract class Contract {

}

@Injectable()
class SimpleContract extends Contract { }

@Injectable()
export class ComplexContract extends Contract { }

@Injectable()
class ContractConsumer {
  // Will default to SimpleContract if nothing else registered
  @Inject()
  contract: Contract;
}

By default, if there is only one candidate without qualification, then that candidate will be used. If multiple candidates are found, then the injection system will bail. To overcome this the end user will need to specify which candidate type should be considered primary:

Code: Example Multiple Candidate Types

import { InjectableFactory } from '@travetto/di';
import { Contract, ComplexContract } from './injectable-multiple-default';

class Config {
  // Complex will be marked as the available Contract
  @InjectableFactory({ primary: true })
  static getContract(complex: ComplexContract): Contract {
    return complex;
  }
}

Non-Framework Dependencies

The module is built around the framework's management of class registration, and being able to decorate the code with @Injectable decorators. There may also be a desire to leverage external code and pull it into the dependency injection framework. This could easily be achieved using a wrapper class that is owned by the framework.

It is also possible to directly reference external types, and they will be converted into unique symbols. These symbols cannot be used manually, but can be leveraged using @Inject decorators.

Code: Example External Dependencies

import { EventEmitter } from 'node:events';
import { Writable } from 'node:stream';

import { Inject, Injectable, InjectableFactory } from '@travetto/di';
import { asFull } from '@travetto/runtime';

class Source {
  @InjectableFactory()
  static emitter(): EventEmitter {
    return new EventEmitter();
  }

  @InjectableFactory(Symbol.for('custom-1'))
  static writable(): Writable {
    return asFull({});
  }

  @InjectableFactory(Symbol.for('custom-2'))
  static writableAlt(): Writable {
    return asFull({});
  }
}

@Injectable()
class Service {
  @Inject()
  emitter: EventEmitter;

  @Inject(Symbol.for('custom-2'))
  writable: Writable;
}

Manual Invocation

Some times you will need to lookup a dependency dynamically, or you want to control the injection process at a more granular level. To achieve that you will need to directly access the DependencyRegistry. The registry allows for requesting a dependency by class reference:

Code: Example of Manual Lookup

import { Injectable, DependencyRegistry } from '@travetto/di';

@Injectable()
class Complex { }

class ManualLookup {
  async invoke() {
    const complex = await DependencyRegistry.getInstance(Complex);
    return complex;
  }
}

Additionally, support for interfaces (over class inheritance) is provided, but requires binding the interface to a concrete class as the interface does not exist at runtime.

Code: Example Interface Injection

import { DependencyRegistry, Inject, Injectable, InjectableFactory } from '@travetto/di';

class TargetConcrete { }

/**
 * @concrete #TargetConcrete
 */
export interface ServiceContract {
  deleteUser(userId: string): Promise<void>;
}

class MyCustomService implements ServiceContract {
  async deleteUser(userId: string): Promise<void> {
    // Do something
  }
}

@Injectable()
class SpecificService {

  @Inject()
  service: ServiceContract;
}

class ManualInvocationOfInterface {
  @InjectableFactory()
  static getCustomService(): Promise<ServiceContract> {
    return DependencyRegistry.getInstance<ServiceContract>(TargetConcrete);
  }
}