Compare commits
9 Commits
Author | SHA1 | Date | |
---|---|---|---|
8bb153fe54 | |||
![]() |
794c1e07c3 | ||
1a67d3f4e3 | |||
042d918d00 | |||
06ae6737fd | |||
81873f3689 | |||
4aa12321e8 | |||
26b35d1e5b | |||
78564b9a76 |
@@ -9,17 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- feat: Add new `IdentifierRequiredError` class for missing identifiers.
|
||||||
|
- feat: Add the option to use the decorators without passing the identifier: In this case, the identifier will be the class name (register) or the property name (inject).
|
||||||
- Add pre release building to release workflow on dev/* branches an version changes.
|
- Add pre release building to release workflow on dev/* branches an version changes.
|
||||||
|
|
||||||
|
|
||||||
### Deprecated
|
### Deprecated
|
||||||
|
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
|
|
||||||
|
- feat!: Disable `experimentalDecorators` and `emitDecoratorMetadata` in the `tsconfig.json` file to reflect the change to the stable decorators api.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- feat!: Update `Register`, `RegisterInstance` and `Inject` decorators to reflect the change to the stable decorators api.
|
||||||
|
- feat!: Update `Inject` Decorator typing to reflect the correct property type.
|
||||||
|
|
||||||
### Security
|
### Security
|
||||||
|
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ts-injex",
|
"name": "ts-injex",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0-.1",
|
||||||
"description": "Simple boilerplate code free dependency injection system for TypeScript.",
|
"description": "Simple boilerplate code free dependency injection system for TypeScript.",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/index.js",
|
||||||
|
@@ -67,6 +67,29 @@ export function test_InjectDecorator(
|
|||||||
expect(instance.getDependency().value).toBe('test-value-init');
|
expect(instance.getDependency().value).toBe('test-value-init');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should inject dependency and run initializer without identifier', () => {
|
||||||
|
container.register('MockDependencyIdentifier', {
|
||||||
|
value: 'test-value',
|
||||||
|
});
|
||||||
|
|
||||||
|
class TestClass {
|
||||||
|
@Inject(undefined, (x: string) => {
|
||||||
|
(x as unknown as { value: string }).value =
|
||||||
|
'test-value-init';
|
||||||
|
|
||||||
|
return x;
|
||||||
|
})
|
||||||
|
MockDependencyIdentifier!: any;
|
||||||
|
|
||||||
|
public getDependency() {
|
||||||
|
return this.MockDependencyIdentifier;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const instance = new TestClass();
|
||||||
|
expect(instance.getDependency().value).toBe('test-value-init');
|
||||||
|
});
|
||||||
|
|
||||||
it('should throw an error when necessary is true and the initializer throws an error', () => {
|
it('should throw an error when necessary is true and the initializer throws an error', () => {
|
||||||
let _error: Error | undefined = undefined;
|
let _error: Error | undefined = undefined;
|
||||||
|
|
||||||
@@ -78,7 +101,7 @@ export function test_InjectDecorator(
|
|||||||
class TestClass {
|
class TestClass {
|
||||||
@Inject(
|
@Inject(
|
||||||
'InitThrowDependencie',
|
'InitThrowDependencie',
|
||||||
() => {
|
(): any => {
|
||||||
throw new Error('Initializer error');
|
throw new Error('Initializer error');
|
||||||
},
|
},
|
||||||
true,
|
true,
|
||||||
@@ -275,6 +298,19 @@ export function test_RegisterDecorator(
|
|||||||
TestClass,
|
TestClass,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should register a dependency without an identifier', () => {
|
||||||
|
@register()
|
||||||
|
class TestClass {
|
||||||
|
private readonly _dependency!: any;
|
||||||
|
|
||||||
|
public getDependency() {
|
||||||
|
return this._dependency;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(container.resolve('TestClass')).toBe(TestClass);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -311,6 +347,23 @@ export function test_RegisterInstanceDecorator(
|
|||||||
).toBe('instance');
|
).toBe('instance');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should register an instance of a dependency with an identifier', () => {
|
||||||
|
@registerInstance()
|
||||||
|
class TestClass {
|
||||||
|
private readonly _dependency!: any;
|
||||||
|
|
||||||
|
public getDependency() {
|
||||||
|
return this._dependency;
|
||||||
|
}
|
||||||
|
|
||||||
|
public mark: string = 'instance';
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(container.resolve<TestClass>('TestClass').mark).toBe(
|
||||||
|
'instance',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('should register an instance of a dependency an run the init function', () => {
|
it('should register an instance of a dependency an run the init function', () => {
|
||||||
@registerInstance(
|
@registerInstance(
|
||||||
'InstanceIdentifier',
|
'InstanceIdentifier',
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
DependencyResolutionError,
|
DependencyResolutionError,
|
||||||
|
IdentifierRequiredError,
|
||||||
InitializationError,
|
InitializationError,
|
||||||
InjectorError,
|
InjectorError,
|
||||||
NoInstantiationMethodError,
|
NoInstantiationMethodError,
|
||||||
@@ -10,17 +11,17 @@ import { InitDelegate } from '../types/InitDelegate';
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A decorator to inject a dependency from a DI (Dependency Injection) container into a class property.
|
* A decorator to inject a dependency from a DI (Dependency Injection) container into a class property.
|
||||||
* @template T The type of the dependency to be injected.
|
* @template TargetType The type of the class to inject the dependency into.
|
||||||
* @template U The type of the property to be injected.
|
* @template DependencyType The type of the dependency to be injected.
|
||||||
* @param identifier The identifier used to resolve the class in the DI container.
|
* @template PropertyType The type of the property to be injected.
|
||||||
* @see {@link Identifier} for more information on identifiers.
|
* @param identifier The {@link Identifier|identifier} used to resolve the dependencie in the DI container or the property name if not provided.
|
||||||
* @param init Optional an initializer function to transform the dependency before injection
|
* @param init An optional initializer {@link InitDelegate|function} to transform the dependency before injection
|
||||||
* or true to instantiate the dependency if it has a constructor.
|
* or true to instantiate the dependency if it has a constructor.
|
||||||
* @see {@link InitDelegate} for more information on initializer functions.
|
|
||||||
* @param necessary If true, throws an error if the dependency is not found.
|
* @param necessary If true, throws an error if the dependency is not found.
|
||||||
* @returns The resolved dependency or undefined if the dependency is not necessary
|
* @returns The resolved dependency or undefined if the dependency is not necessary
|
||||||
* and not found, or throws an error if the dependency is necessary and not found.
|
* and not found, or throws an error if the dependency is necessary and not found.
|
||||||
* @throws **Only throws errors if the dependency is necessary.**
|
* @throws **Only throws errors if the dependency is necessary.**
|
||||||
|
* @throws An {@link IdentifierRequiredError} if the identifier is not provided and the class name is not available.
|
||||||
* @throws A {@link DependencyResolutionError} if the dependency is not found.
|
* @throws A {@link DependencyResolutionError} if the dependency is not found.
|
||||||
* @throws A {@link InjectorError} if an error occurs during the injection process.
|
* @throws A {@link InjectorError} if an error occurs during the injection process.
|
||||||
* @throws A {@link NoInstantiationMethodError} if the dependency does not have a constructor.
|
* @throws A {@link NoInstantiationMethodError} if the dependency does not have a constructor.
|
||||||
@@ -40,70 +41,86 @@ import { InitDelegate } from '../types/InitDelegate';
|
|||||||
* }
|
* }
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export function Inject<T, U>(
|
export function Inject<TargetType, DependencyType, PropertyType>(
|
||||||
identifier: Identifier,
|
identifier?: Identifier,
|
||||||
init?: InitDelegate<T, U> | true,
|
init?: InitDelegate<DependencyType, PropertyType> | true,
|
||||||
necessary = true,
|
necessary = true,
|
||||||
) {
|
) {
|
||||||
return function (target: unknown, propertyKey: string | symbol): void {
|
return function (
|
||||||
|
constructor: undefined,
|
||||||
|
context: ClassFieldDecoratorContext<TargetType> & {
|
||||||
|
name: PropertyType;
|
||||||
|
},
|
||||||
|
): void {
|
||||||
|
const _identifier = identifier ?? context.name;
|
||||||
|
|
||||||
|
if (_identifier == null && necessary === true)
|
||||||
|
throw new IdentifierRequiredError();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Function to evaluate the dependency lazily
|
* Function to evaluate the dependency lazily
|
||||||
* to avoid circular dependencies, not found dependencies, etc.
|
* to avoid circular dependencies, not found dependencies, etc.
|
||||||
* @returns The resolved dependency or undefined if the dependency is not found.
|
* @returns The resolved dependency or undefined if the dependency is not found.
|
||||||
*/
|
*/
|
||||||
const resolve = (): T | undefined => {
|
const resolve = (): DependencyType | undefined => {
|
||||||
return TSinjex.getInstance().resolve<T>(identifier, necessary);
|
return TSinjex.getInstance().resolve<DependencyType>(
|
||||||
|
_identifier,
|
||||||
|
necessary,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
Object.defineProperty(target, propertyKey, {
|
context.addInitializer(function (this: TargetType) {
|
||||||
get() {
|
Object.defineProperty(this, context.name, {
|
||||||
let instance: T | U | undefined;
|
get() {
|
||||||
|
let instance: DependencyType | PropertyType | undefined;
|
||||||
|
|
||||||
const dependency: T | undefined = tryAndCatch(
|
const dependency: DependencyType | undefined = tryAndCatch(
|
||||||
() => resolve(),
|
() => resolve(),
|
||||||
necessary,
|
necessary,
|
||||||
identifier,
|
_identifier,
|
||||||
DependencyResolutionError,
|
DependencyResolutionError,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (dependency != null) {
|
if (dependency != null) {
|
||||||
const initFunction: (() => U) | undefined =
|
const initFunction: (() => PropertyType) | undefined =
|
||||||
typeof init === 'function' && dependency != null
|
typeof init === 'function' && dependency != null
|
||||||
? (): U => init(dependency)
|
? (): PropertyType => init(dependency)
|
||||||
: init === true && hasConstructor(dependency)
|
: init === true && hasConstructor(dependency)
|
||||||
? (): U => new dependency() as U
|
? (): PropertyType =>
|
||||||
: undefined;
|
new dependency() as PropertyType
|
||||||
|
: undefined;
|
||||||
|
|
||||||
if (init == null) instance = dependency;
|
if (init == null) instance = dependency;
|
||||||
else if (initFunction != null)
|
else if (initFunction != null)
|
||||||
instance = tryAndCatch(
|
instance = tryAndCatch(
|
||||||
initFunction,
|
initFunction,
|
||||||
necessary,
|
necessary,
|
||||||
identifier,
|
_identifier,
|
||||||
InitializationError,
|
InitializationError,
|
||||||
);
|
);
|
||||||
else if (necessary)
|
else if (necessary)
|
||||||
throw new NoInstantiationMethodError(identifier);
|
throw new NoInstantiationMethodError(_identifier);
|
||||||
} else if (necessary)
|
} else if (necessary)
|
||||||
throw new DependencyResolutionError(identifier);
|
throw new DependencyResolutionError(_identifier);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace itself with the resolved dependency
|
||||||
|
* for performance reasons.
|
||||||
|
*/
|
||||||
|
Object.defineProperty(this, context.name, {
|
||||||
|
value: instance,
|
||||||
|
writable: false,
|
||||||
|
enumerable: false,
|
||||||
|
configurable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return instance;
|
||||||
|
},
|
||||||
/**
|
/**
|
||||||
* Replace itself with the resolved dependency
|
* Make the property configurable to allow replacing it
|
||||||
* for performance reasons.
|
|
||||||
*/
|
*/
|
||||||
Object.defineProperty(this, propertyKey, {
|
configurable: true,
|
||||||
value: instance,
|
});
|
||||||
writable: false,
|
|
||||||
enumerable: false,
|
|
||||||
configurable: false,
|
|
||||||
});
|
|
||||||
|
|
||||||
return instance;
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Make the property configurable to allow replacing it
|
|
||||||
*/
|
|
||||||
configurable: true,
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@@ -1,14 +1,14 @@
|
|||||||
|
import { IdentifierRequiredError } from 'src/interfaces/Exceptions';
|
||||||
import { TSinjex } from '../classes/TSinjex';
|
import { TSinjex } from '../classes/TSinjex';
|
||||||
import { Identifier } from '../types/Identifier';
|
import { Identifier } from '../types/Identifier';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A decorator to register a class in the **TSinjex** DI (Dependency Injection) container.
|
* A decorator to register a class in the **TSinjex** DI (Dependency Injection) container.
|
||||||
* @template TargetType The type of the class to be registered.
|
* @template TargetType The type of the class to be registered.
|
||||||
* @param identifier The identifier used to register the class in the DI container.
|
* @param identifier The {@link Identifier|identifier} used to register the class in the DI container or the class name if not provided.
|
||||||
* @see {@link Identifier} for more information on identifiers.
|
* @param deprecated If true, the dependency is deprecated and a warning is logged only once upon the first resolution of the dependency.
|
||||||
* @param deprecated If true, the dependency is deprecated and a warning
|
|
||||||
* is logged only once upon the first resolution of the dependency.
|
|
||||||
* @returns The decorator function to be applied on the class.
|
* @returns The decorator function to be applied on the class.
|
||||||
|
* @throws An {@link IdentifierRequiredError} if the identifier is not provided and the class name is not available.
|
||||||
* @example
|
* @example
|
||||||
* ```ts
|
* ```ts
|
||||||
* \@Register('MyClassIdentifier')
|
* \@Register('MyClassIdentifier')
|
||||||
@@ -19,12 +19,16 @@ import { Identifier } from '../types/Identifier';
|
|||||||
*/
|
*/
|
||||||
export function Register<
|
export function Register<
|
||||||
TargetType extends new (...args: unknown[]) => InstanceType<TargetType>,
|
TargetType extends new (...args: unknown[]) => InstanceType<TargetType>,
|
||||||
>(identifier: Identifier, deprecated?: boolean) {
|
>(identifier?: Identifier, deprecated?: boolean) {
|
||||||
return function (constructor: TargetType, ...args: unknown[]): void {
|
return function (
|
||||||
// Get the instance of the DI container
|
constructor: TargetType,
|
||||||
const diContainer = TSinjex.getInstance();
|
context: ClassDecoratorContext<TargetType>,
|
||||||
|
) {
|
||||||
|
const _identifier = identifier ?? context.name;
|
||||||
|
|
||||||
// Register the class in the DI container
|
if (_identifier == null) throw new IdentifierRequiredError();
|
||||||
diContainer.register(identifier, constructor, deprecated);
|
|
||||||
|
const diContainer = TSinjex.getInstance();
|
||||||
|
diContainer.register(_identifier, constructor, deprecated);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@@ -1,3 +1,4 @@
|
|||||||
|
import { IdentifierRequiredError } from 'src/interfaces/Exceptions';
|
||||||
import { TSinjex } from '../classes/TSinjex';
|
import { TSinjex } from '../classes/TSinjex';
|
||||||
import { Identifier } from '../types/Identifier';
|
import { Identifier } from '../types/Identifier';
|
||||||
import { InitDelegate } from '../types/InitDelegate';
|
import { InitDelegate } from '../types/InitDelegate';
|
||||||
@@ -5,12 +6,11 @@ import { InitDelegate } from '../types/InitDelegate';
|
|||||||
/**
|
/**
|
||||||
* A decorator to register an instance of a class in the DI (Dependency Injection) container.
|
* A decorator to register an instance of a class in the DI (Dependency Injection) container.
|
||||||
* @template TargetType The type of the class whose instance is to be registered.
|
* @template TargetType The type of the class whose instance is to be registered.
|
||||||
* @param identifier The identifier used to register the instance in the DI container.
|
* @param identifier The {@link Identifier|identifier} used to register the class in the DI container or the class name if not provided.
|
||||||
* @see {@link Identifier} for more information on identifiers.
|
* @param init An optional initializer {@link InitDelegate|function} which get the constructor of the class
|
||||||
* @param init An optional initializer function which get the constructor of the class
|
|
||||||
* as input and returns an instance of the class.
|
* as input and returns an instance of the class.
|
||||||
* @see {@link InitDelegate} for more information on initializer functions.
|
|
||||||
* @returns The decorator function to be applied on the class.
|
* @returns The decorator function to be applied on the class.
|
||||||
|
* @throws An {@link IdentifierRequiredError} if the identifier is not provided and the class name is not available.
|
||||||
* @example
|
* @example
|
||||||
* ```ts
|
* ```ts
|
||||||
* \@RegisterInstance('MyClassInstanceIdentifier', (constructor) => new constructor())
|
* \@RegisterInstance('MyClassInstanceIdentifier', (constructor) => new constructor())
|
||||||
@@ -22,43 +22,51 @@ import { InitDelegate } from '../types/InitDelegate';
|
|||||||
export function RegisterInstance<
|
export function RegisterInstance<
|
||||||
TargetType extends new (..._args: unknown[]) => InstanceType<TargetType>,
|
TargetType extends new (..._args: unknown[]) => InstanceType<TargetType>,
|
||||||
>(
|
>(
|
||||||
identifier: Identifier,
|
identifier?: Identifier,
|
||||||
init?: InitDelegate<
|
init?: InitDelegate<
|
||||||
TargetType & { new (..._args: unknown[]): InstanceType<TargetType> },
|
TargetType & { new (..._args: unknown[]): InstanceType<TargetType> },
|
||||||
InstanceType<TargetType>
|
InstanceType<TargetType>
|
||||||
>,
|
>,
|
||||||
) {
|
) {
|
||||||
return function (constructor: TargetType, ...args: unknown[]): void {
|
return function (
|
||||||
// Get the instance of the DI container
|
constructor: TargetType,
|
||||||
|
context: ClassDecoratorContext<TargetType>,
|
||||||
|
): void {
|
||||||
|
const _identifier = identifier ?? context.name;
|
||||||
|
|
||||||
|
if (_identifier == null) throw new IdentifierRequiredError();
|
||||||
|
|
||||||
const diContainer = TSinjex.getInstance();
|
const diContainer = TSinjex.getInstance();
|
||||||
let instance: InstanceType<TargetType>;
|
let instance: InstanceType<TargetType>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the instance of the class
|
||||||
|
* and replace the lazy proxy with the instance
|
||||||
|
* for performance optimization.
|
||||||
|
*/
|
||||||
|
const getAndRegisterInstance = (): void => {
|
||||||
|
if (instance == null) {
|
||||||
|
if (init) {
|
||||||
|
instance = init(constructor);
|
||||||
|
} else {
|
||||||
|
instance = new constructor();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
diContainer.register(_identifier, instance);
|
||||||
|
};
|
||||||
|
|
||||||
// Create a proxy to instantiate the class when needed (Lazy Initialization)
|
// Create a proxy to instantiate the class when needed (Lazy Initialization)
|
||||||
let lazyProxy: unknown = new Proxy(
|
const lazyProxy: unknown = new Proxy(
|
||||||
{},
|
{},
|
||||||
{
|
{
|
||||||
get(target, prop, receiver) {
|
get(_target, prop, _receiver) {
|
||||||
if (instance == null) {
|
getAndRegisterInstance();
|
||||||
if (init) {
|
|
||||||
instance = init(constructor);
|
|
||||||
} else {
|
|
||||||
instance = new constructor(...args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lazyProxy = instance;
|
|
||||||
|
|
||||||
// Return the requested property of the instance
|
// Return the requested property of the instance
|
||||||
return instance[prop as keyof InstanceType<TargetType>];
|
return instance[prop as keyof InstanceType<TargetType>];
|
||||||
},
|
},
|
||||||
set(target, prop, value, receiver) {
|
set(_target, prop, value, _receiver) {
|
||||||
if (instance == null) {
|
getAndRegisterInstance();
|
||||||
if (init) {
|
|
||||||
instance = init(constructor);
|
|
||||||
} else {
|
|
||||||
instance = new constructor(...args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lazyProxy = instance;
|
|
||||||
|
|
||||||
// Set the requested property of the instance
|
// Set the requested property of the instance
|
||||||
return (instance[prop as keyof InstanceType<TargetType>] =
|
return (instance[prop as keyof InstanceType<TargetType>] =
|
||||||
@@ -67,7 +75,6 @@ export function RegisterInstance<
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Register the lazy proxy in the DI container
|
diContainer.register(_identifier, lazyProxy);
|
||||||
diContainer.register(identifier, lazyProxy);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@@ -15,6 +15,19 @@ export class TSinjexError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Error class for missing identifiers in {@link ITSinjex} methods.
|
||||||
|
*/
|
||||||
|
export class IdentifierRequiredError extends TSinjexError {
|
||||||
|
/**
|
||||||
|
* Creates a new instance of {@link IdentifierRequiredError}
|
||||||
|
*/
|
||||||
|
constructor() {
|
||||||
|
super('Identifier is required.');
|
||||||
|
this.name = 'TSinjexIdentifierRequiredError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Error class for dependency resolution errors in {@link ITSinjex}.
|
* Error class for dependency resolution errors in {@link ITSinjex}.
|
||||||
* @see {@link ITSinjex.resolve}
|
* @see {@link ITSinjex.resolve}
|
||||||
|
@@ -18,8 +18,6 @@
|
|||||||
"importHelpers": true,
|
"importHelpers": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"resolveJsonModule": true,
|
"resolveJsonModule": true,
|
||||||
"experimentalDecorators": true,
|
|
||||||
"emitDecoratorMetadata": true,
|
|
||||||
"strictNullChecks": true,
|
"strictNullChecks": true,
|
||||||
"strictPropertyInitialization": true,
|
"strictPropertyInitialization": true,
|
||||||
"lib": [
|
"lib": [
|
||||||
|
Reference in New Issue
Block a user