nestjs-telegraf/lib/telegraf.module.ts

85 lines
2.2 KiB
TypeScript
Raw Normal View History

import { DiscoveryModule } from '@nestjs/core';
import { Module, DynamicModule, Provider } from '@nestjs/common';
import {
2020-03-19 16:21:35 +03:00
TelegrafModuleOptions,
TelegrafModuleAsyncOptions,
TelegrafOptionsFactory,
} from './interfaces';
import { TELEGRAF_MODULE_OPTIONS } from './telegraf.constants';
2020-12-26 16:11:09 +03:00
import { TelegrafMetadataAccessor } from './telegraf.metadata-accessor';
import { TelegrafExplorer } from './telegraf.explorer';
import { TelegrafProvider } from './telegraf.provider';
2019-02-28 11:29:26 +03:00
@Module({
imports: [DiscoveryModule],
providers: [TelegrafMetadataAccessor, TelegrafExplorer],
})
export class TelegrafModule {
2020-05-03 11:06:25 +03:00
public static forRoot(options: TelegrafModuleOptions): DynamicModule {
const providers = [...this.createProviders(options), TelegrafProvider];
2019-02-28 11:29:26 +03:00
return {
2020-01-12 01:15:32 +03:00
module: TelegrafModule,
providers,
exports: providers,
};
2019-02-28 11:29:26 +03:00
}
private static createProviders(options: TelegrafModuleOptions): Provider[] {
return [
{
provide: TELEGRAF_MODULE_OPTIONS,
useValue: options,
},
];
}
2020-03-19 16:21:35 +03:00
public static forRootAsync(
options: TelegrafModuleAsyncOptions,
): DynamicModule {
const providers = [...this.createAsyncProviders(options), TelegrafProvider];
return {
2020-03-19 16:21:35 +03:00
module: TelegrafModule,
imports: options.imports || [],
providers,
exports: providers,
};
}
private static createAsyncProviders(
options: TelegrafModuleAsyncOptions,
): Provider[] {
if (options.useExisting || options.useFactory) {
return [this.createAsyncOptionsProvider(options)];
}
return [
this.createAsyncOptionsProvider(options),
{
provide: options.useClass,
useClass: options.useClass,
},
];
}
private static createAsyncOptionsProvider(
options: TelegrafModuleAsyncOptions,
): Provider {
if (options.useFactory) {
return {
provide: TELEGRAF_MODULE_OPTIONS,
useFactory: options.useFactory,
inject: options.inject || [],
};
}
return {
provide: TELEGRAF_MODULE_OPTIONS,
useFactory: async (optionsFactory: TelegrafOptionsFactory) =>
await optionsFactory.createTelegrafOptions(),
inject: [options.useExisting || options.useClass],
};
}
2019-02-28 11:29:26 +03:00
}