Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion app/src/shared/config/dynamic.config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ interface OptionProviderRegister {
injects?: Type[];
}

const REGISTER_TOKENS: Record<string, Type> = {};

/**
* A utility module in NestJS for dynamically registering providers and modules.
*
Expand All @@ -16,6 +18,23 @@ interface OptionProviderRegister {
*/
@Module({})
export class DynamicConfigModule {
private static setClassImplementation<T>(useClass: Type<T>) {
const interfaceName = useClass.name.replace(/Impl$/, '');
REGISTER_TOKENS[interfaceName] = useClass;
}

static getClassImplementation<T = any>(propertyKey: string): Type<T> {
if (!propertyKey || propertyKey?.length === 0) {
throw new Error(`Property '${propertyKey}' is required.`);
}
const interfaceName = propertyKey.charAt(0).toUpperCase() + propertyKey.slice(1);
const useClass = REGISTER_TOKENS[interfaceName];
if (!useClass) {
throw new Error(`Class not registered for the ${interfaceName}`);
}
return useClass;
}

/**
* Dynamically registers a single provider with optional dependencies and exports it.
*
Expand All @@ -39,11 +58,11 @@ export class DynamicConfigModule {
* ```
*/
private static forProvider<T>(useClass: Type<T>, injects?: Type[]): Provider {
this.setClassImplementation(useClass);
if (injects && injects.length > 0) {
return {
provide: useClass,
useFactory: (...args: any[]) => new useClass(...args),
useClass,
inject: injects,
};
}
Expand Down
1 change: 1 addition & 0 deletions app/src/shared/config/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './dynamic.config.module';
export * from './inject.auto.decorator';
9 changes: 9 additions & 0 deletions app/src/shared/config/inject.auto.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Inject } from '@nestjs/common';
import { DynamicConfigModule } from '@shared/config/index';

export function InjectAuto(): PropertyDecorator {
return async (target: Object, propertyKey: string) => {
const classImplementation = DynamicConfigModule.getClassImplementation(propertyKey);
Inject(classImplementation)(target, propertyKey);
};
}
Loading