Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created November 14, 2024 08:11
Show Gist options
  • Save guiseek/d576357cde56dd8426c1648f4f8478ab to your computer and use it in GitHub Desktop.
Save guiseek/d576357cde56dd8426c1648f4f8478ab to your computer and use it in GitHub Desktop.
Create providers
export type Abstract<T = any> = abstract new (...params: any[]) => T;
import { Abstract } from './abstract';
import { Type } from './type';
type MapToAbstract<T> = T extends [infer First, ...infer Rest]
? [Abstract<First> | string, ...MapToAbstract<Rest>]
: [];
export type ConstructorAbstractParameters<T extends Type> = MapToAbstract<
ConstructorParameters<T>
>;
import { Type } from './type';
type MapToType<T> = T extends [infer First, ...infer Rest]
? [Type<First> | string, ...MapToType<Rest>]
: [];
export type ConstructorTypeParameters<T extends Type> = MapToType<
ConstructorParameters<T>
>;
import {
Type,
ConstructorTypeParameters,
ConstructorAbstractParameters,
} from '@typescript-stack/shared-api-global';
export function createConstructorProvider<T extends Type>(
constructor: T,
dependencies: ConstructorTypeParameters<T> | ConstructorAbstractParameters<T>
) {
return {
provide: constructor,
useFactory(...params: ConstructorParameters<T>) {
return new constructor(...params);
},
deps: dependencies,
};
}
import {
Type,
Abstract,
ConstructorTypeParameters,
ConstructorAbstractParameters,
} from '@typescript-stack/shared-api-global';
export function createReplaceableProvider<A extends Abstract, T extends Type>(
constructor: A,
implementation: T,
dependencies: ConstructorTypeParameters<T> | ConstructorAbstractParameters<T>
) {
return {
provide: constructor,
useFactory(...params: ConstructorParameters<T>) {
return new implementation(...params);
},
deps: dependencies,
};
}
export function createValueProvider<K, T>(provide: K, useValue: T) {
return { provide, useValue };
}
export interface Type<T = any> extends NewableFunction {
new (...params: any[]): T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment