DI
This module is required and peer-dependent for @buny/core
package.
Introduction
DI package offers many decorators that helps you with dependency injection and provides utilities for your classes.
Installation
To install the package, run the following command:
npm install @buny/di
Usage
To use @buny/di
, import DI package and use decorators in your classes.
import {Usable, Optional, Use, Cache} from "@buny/di";
@Usable()
class MyClass {
@Optional()
@Use()
private myService: MyService;
@Cache()
private calculate() {
return this.myService.calculate();
}
}
Decorators
@Usable()
This decorator marks a class as usable for dependency injection, and registers it in container.
Example
import {Usable} from "@buny/di";
@Usable()
class MyClass {
}
Parameters
options
- object
(optional)
token
- Token to use for registration. Default is class name.dependencies
- Array of dependencies the class depends on.scope
- Scope of the class. Default isSingleton
.
@Use()
This decorator marks a property as a dependency, and injects the dependency from container when the class is resolved.
for methods, it injects the dependency when the method is invoked by the ioc invoke utility.
Example
import {Use} from "@buny/di";
class MyClass {
@Use() myService: MyService;
constructor(@Use() myService: MyService) {
}
private method(@Use() myService: MyService) {
}
}
Parameters
token
- Token
(optional) - Token to use for injection. Default is property type.
@Optional()
This decorator marks a property as optional, and does not throw an error if the dependency is not found in the container.
Example
import {Optional, Use} from "@buny/di";
class MyClass {
@Optional() @Use() myService: MyService;
}
@Env()
This decorator marks a property as an environment variable, and injects the value from the environment.
Example
import {Env} from "@buny/di";
class MyClass {
@Env("PORT") port: number;
}
Parameters
name
- string
- Environment variable name.
@Cache()
This decorator marks a method as cacheable, and caches the result of the method.
Example
import {Cache} from "@buny/di";
class MyClass {
@Cache() calculate() {
return 1 + 1;
}
}
@Debounce()
This decorator marks a method as debounced, and debounces the method.
Example
import {Debounce} from "@buny/di";
class MyClass {
@Debounce(1000) calculate() {
return 1 + 1;
}
}
Parameters
ms
- number
- Debounce time in milliseconds.
@Delay()
This decorator marks a method as delayed, and delays the method.
Example
import {Delay} from "@buny/di";
class MyClass {
@Delay(1000) calculate() {
return 1 + 1;
}
}
Parameters
ms
- number
- Delay time in milliseconds.
@Wrap()
This decorator receive multiple decorators and wraps them.
Example
import {Wrap, Delay} from "@buny/di";
class MyClass {
@Wrap([
Delay(1000),
Delay(2000),
]) calculate() {
return 1 + 1;
}
}