|
| 1 | +import { |
| 2 | + DynamicModule, |
| 3 | + Global, |
| 4 | + Inject, |
| 5 | + Module, |
| 6 | + Provider, |
| 7 | + Type, |
| 8 | +} from '@nestjs/common'; |
| 9 | +import { StorageService } from './storage.service'; |
| 10 | + |
| 11 | +import { STORAGE_MODULE_OPTIONS } from './storage.constants'; |
| 12 | +import { StorageModuleOptions, StorageOptionsFactory } from './interfaces'; |
| 13 | +import { ModuleRef } from '@nestjs/core'; |
| 14 | +import { StorageModuleAsyncOptions } from './interfaces/storage-module-async-options'; |
| 15 | +@Global() |
| 16 | +@Module({}) |
| 17 | +export class StorageCoreModule { |
| 18 | + constructor( |
| 19 | + @Inject(STORAGE_MODULE_OPTIONS) |
| 20 | + private readonly options: StorageModuleOptions, |
| 21 | + private readonly moduleRef: ModuleRef, |
| 22 | + ) {} |
| 23 | + |
| 24 | + static forRoot(options: StorageModuleOptions): DynamicModule { |
| 25 | + const storageModuleOptions: Provider = { |
| 26 | + provide: STORAGE_MODULE_OPTIONS, |
| 27 | + useValue: options, |
| 28 | + }; |
| 29 | + |
| 30 | + return { |
| 31 | + module: StorageCoreModule, |
| 32 | + providers: [storageModuleOptions, StorageService], |
| 33 | + exports: [StorageService], |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + static forRootAsync(options: StorageModuleAsyncOptions): DynamicModule { |
| 38 | + const asyncProviders = this.createAsyncProviders(options); |
| 39 | + |
| 40 | + return { |
| 41 | + module: StorageCoreModule, |
| 42 | + imports: options.imports, |
| 43 | + providers: [...asyncProviders, StorageService], |
| 44 | + exports: [StorageService], |
| 45 | + }; |
| 46 | + } |
| 47 | + |
| 48 | + private static createAsyncProviders( |
| 49 | + options: StorageModuleAsyncOptions, |
| 50 | + ): Provider[] { |
| 51 | + if (options.useFactory) { |
| 52 | + return [this.createAsyncOptionsProvider(options)]; |
| 53 | + } |
| 54 | + const useClass = options.useClass as Type<StorageOptionsFactory>; |
| 55 | + return [ |
| 56 | + this.createAsyncOptionsProvider(options), |
| 57 | + { |
| 58 | + provide: useClass, |
| 59 | + useClass, |
| 60 | + }, |
| 61 | + ]; |
| 62 | + } |
| 63 | + |
| 64 | + private static createAsyncOptionsProvider( |
| 65 | + options: StorageModuleAsyncOptions, |
| 66 | + ): Provider { |
| 67 | + if (options.useFactory) { |
| 68 | + return { |
| 69 | + provide: STORAGE_MODULE_OPTIONS, |
| 70 | + useFactory: options.useFactory, |
| 71 | + inject: options.inject || [], |
| 72 | + }; |
| 73 | + } |
| 74 | + |
| 75 | + const inject = [options.useClass as Type<StorageOptionsFactory>]; |
| 76 | + |
| 77 | + return { |
| 78 | + provide: STORAGE_MODULE_OPTIONS, |
| 79 | + useFactory: async (optionsFactory: StorageOptionsFactory) => |
| 80 | + optionsFactory.createStorageOptions(), |
| 81 | + inject, |
| 82 | + }; |
| 83 | + } |
| 84 | +} |
0 commit comments