|
| 1 | +import { DynamicModule, Module, Provider } from '@nestjs/common'; |
| 2 | +import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util'; |
| 3 | +import { MULTIPART_MODULE_OPTIONS } from './files.constants'; |
| 4 | +import { |
| 5 | + MultipartModuleAsyncOptions, |
| 6 | + MultipartModuleOptions, |
| 7 | + MultipartOptionsFactory, |
| 8 | +} from './interfaces/files-upload-module.interface'; |
| 9 | +import { MULTIPART_MODULE_ID } from './multipart.constants'; |
| 10 | + |
| 11 | +@Module({}) |
| 12 | +export class MultipartModule { |
| 13 | + static register(options: MultipartModuleOptions = {}): DynamicModule { |
| 14 | + return { |
| 15 | + module: MultipartModule, |
| 16 | + providers: [ |
| 17 | + { provide: MULTIPART_MODULE_OPTIONS, useValue: options }, |
| 18 | + { |
| 19 | + provide: MULTIPART_MODULE_ID, |
| 20 | + useValue: randomStringGenerator(), |
| 21 | + }, |
| 22 | + ], |
| 23 | + exports: [MULTIPART_MODULE_OPTIONS], |
| 24 | + }; |
| 25 | + } |
| 26 | + |
| 27 | + static registerAsync(options: MultipartModuleAsyncOptions): DynamicModule { |
| 28 | + return { |
| 29 | + module: MultipartModule, |
| 30 | + imports: options.imports, |
| 31 | + providers: [ |
| 32 | + ...this.createAsyncProviders(options), |
| 33 | + { |
| 34 | + provide: MULTIPART_MODULE_ID, |
| 35 | + useValue: randomStringGenerator(), |
| 36 | + }, |
| 37 | + ], |
| 38 | + exports: [MULTIPART_MODULE_OPTIONS], |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + private static createAsyncProviders( |
| 43 | + options: MultipartModuleAsyncOptions, |
| 44 | + ): Provider[] { |
| 45 | + if (options.useExisting || options.useFactory) { |
| 46 | + return [this.createAsyncOptionsProvider(options)]; |
| 47 | + } |
| 48 | + return [ |
| 49 | + this.createAsyncOptionsProvider(options), |
| 50 | + { |
| 51 | + provide: options.useClass, |
| 52 | + useClass: options.useClass, |
| 53 | + }, |
| 54 | + ]; |
| 55 | + } |
| 56 | + |
| 57 | + private static createAsyncOptionsProvider( |
| 58 | + options: MultipartModuleAsyncOptions, |
| 59 | + ): Provider { |
| 60 | + if (options.useFactory) { |
| 61 | + return { |
| 62 | + provide: MULTIPART_MODULE_OPTIONS, |
| 63 | + useFactory: options.useFactory, |
| 64 | + inject: options.inject || [], |
| 65 | + }; |
| 66 | + } |
| 67 | + return { |
| 68 | + provide: MULTIPART_MODULE_OPTIONS, |
| 69 | + useFactory: async (optionsFactory: MultipartOptionsFactory) => |
| 70 | + optionsFactory.createMultipartOptions(), |
| 71 | + inject: [options.useExisting || options.useClass], |
| 72 | + }; |
| 73 | + } |
| 74 | +} |
0 commit comments