|
| 1 | +import { Module } from '../decorators'; |
| 2 | +import { DynamicModule, Provider } from '../interfaces'; |
| 3 | +import { CACHE_MANAGER, CACHE_MODULE_OPTIONS } from './cache.constants'; |
| 4 | +import { createCacheManager } from './cache.providers'; |
| 5 | +import { |
| 6 | + CacheModuleAsyncOptions, |
| 7 | + CacheModuleOptions, |
| 8 | + CacheOptionsFactory, |
| 9 | +} from './interfaces/cache-module.interface'; |
| 10 | + |
| 11 | +@Module({ |
| 12 | + providers: [createCacheManager()], |
| 13 | + exports: [CACHE_MANAGER], |
| 14 | +}) |
| 15 | +export class CacheModule { |
| 16 | + static register(options: CacheModuleOptions = {}): DynamicModule { |
| 17 | + return { |
| 18 | + module: CacheModule, |
| 19 | + providers: [{ provide: CACHE_MODULE_OPTIONS, useValue: options }], |
| 20 | + }; |
| 21 | + } |
| 22 | + |
| 23 | + static registerAsync(options: CacheModuleAsyncOptions): DynamicModule { |
| 24 | + return { |
| 25 | + module: CacheModule, |
| 26 | + imports: options.imports, |
| 27 | + providers: this.createAsyncProviders(options), |
| 28 | + }; |
| 29 | + } |
| 30 | + |
| 31 | + private static createAsyncProviders( |
| 32 | + options: CacheModuleAsyncOptions, |
| 33 | + ): Provider[] { |
| 34 | + if (options.useExisting || options.useFactory) { |
| 35 | + return [this.createAsyncOptionsProvider(options)]; |
| 36 | + } |
| 37 | + return [ |
| 38 | + this.createAsyncOptionsProvider(options), |
| 39 | + { |
| 40 | + provide: options.useClass, |
| 41 | + useClass: options.useClass, |
| 42 | + }, |
| 43 | + ]; |
| 44 | + } |
| 45 | + |
| 46 | + private static createAsyncOptionsProvider( |
| 47 | + options: CacheModuleAsyncOptions, |
| 48 | + ): Provider { |
| 49 | + if (options.useFactory) { |
| 50 | + return { |
| 51 | + provide: CACHE_MODULE_OPTIONS, |
| 52 | + useFactory: options.useFactory, |
| 53 | + inject: options.inject || [], |
| 54 | + }; |
| 55 | + } |
| 56 | + return { |
| 57 | + provide: CACHE_MODULE_OPTIONS, |
| 58 | + useFactory: async (optionsFactory: CacheOptionsFactory) => |
| 59 | + await optionsFactory.createCacheOptions(), |
| 60 | + inject: [options.useExisting || options.useClass], |
| 61 | + }; |
| 62 | + } |
| 63 | +} |
0 commit comments