Files
Typescript-Dependency-Manager/readme.md
Robin Chappatte 744d1eb6ef fixes typing
2024-05-31 18:05:13 +02:00

68 lines
2.0 KiB
Markdown

# 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:
```typescript
import { DependencyManager } from 'dependency-manager/mod.ts'
const manager = new DependencyManager()
```
2. Register dependencies by giving the manager an identifier and a provider:
```typescript
manager.register('dependency-identifier', () => 'value');
```
3. Get the dependency by giving the manager its identifier (always asynchrone):
```typescript
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:
```typescript
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:
```typescript
class MyDependency {}
const a = await manager.resolve(MyDependecy); //< `a` is of type `MyDependency`
const b = await manager.resolve('dependency-identifier'); //< `b` is of type `unknown`
const c = await manager.resolve<number>('dependency-identifier'); //< `c` is of type `number`
```
## 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