2024-05-31 14:58:32 +02:00
2024-05-21 16:14:58 +02:00

Dependency manager

This lib provides a simplistic dependency manager.

Features

  • Resolves dependencies only when they are needed
  • Detect circular dependency
  • Accept any valid Map key as dependency identifier
    • Infer the dependency type from the dependency identifier if the later is a class

Usage

  1. Create a manager:
import { DependencyManager } from 'dependency-manager/mod.ts'

const manager = new DependencyManager()
  1. Register dependencies by giving the manager an identifier and a provider:
manager.register('dependency-identifier', () => 'value');
  1. Get the dependency by giving the manager its identifier (always asynchrone):
const value = await manager.resolve('dependency-identifier');

Providers

Providers are functions that are called when resolving the dependency for the first time. They receive the dependency manager as parameter, and should return the dependency value, or a promise that resolves to it.

Example of the registration of a dependency which provider uses another dependency:

async function provider(manager: DependencyManager) {
  const value = await manager.resolve('dependencyIdentifier');
  return `The value is: ${valueA}`;
}
manager.register('other-identifier', provider);

Identifiers and typing

Any valid Map key can be used as identifier, but using a class allow the return value of the resolve method to be automatically typed:

class MyDependency {}

manager.register(MyDependency, () => new MyDependency());
const a = await manager.resolve(MyDependecy); //< `a` is of type `MyDependency`

Otherwise you can provide the type as type argument:

function provider() {
  return 'foo'
}
manager.register('my-dependency-identifier', provider);
const a = await manager.resolve('my-dependency-identifier'); //< `a` is of type `unknown`
const b = await manager.resolve<string>('my-dependency-identifier'); //< `b` is of type `string`

Errors

The register method throw an error if:

  • the name is already used.

The resolve method throw an error if:

  • the name doesn't exist (if no module has been registred with the given name).
  • a circular dependency is detected
Description
No description provided
Readme 38 KiB
v2.0.0 Latest
2024-06-12 18:15:35 +02:00
Languages
TypeScript 100%