|
| 1 | +import { ClientConfig, PubSub } from '@google-cloud/pubsub'; |
| 2 | +import { |
| 3 | + ClassProvider, |
| 4 | + DynamicModule, |
| 5 | + Global, |
| 6 | + Module, |
| 7 | + Provider, |
| 8 | +} from '@nestjs/common'; |
| 9 | +import { PUBSUB_MODULE, PUBSUB_TOKEN } from './pubsub.constants'; |
| 10 | +import { PubsubAsyncOptions, PubsubOptionsFactory } from './pubsub.interface'; |
| 11 | + |
| 12 | +function getClient(options: ClientConfig) { |
| 13 | + return new PubSub(options); |
| 14 | +} |
| 15 | + |
| 16 | +function createProvider(options: ClientConfig): Provider<PubSub> { |
| 17 | + return { |
| 18 | + provide: PUBSUB_TOKEN, |
| 19 | + useValue: getClient(options), |
| 20 | + }; |
| 21 | +} |
| 22 | + |
| 23 | +function createAsyncOptionsProvider({ |
| 24 | + inject, |
| 25 | + useFactory, |
| 26 | + useClass, |
| 27 | + useExisting, |
| 28 | +}: PubsubAsyncOptions): Provider { |
| 29 | + if (useFactory) { |
| 30 | + return { |
| 31 | + provide: PUBSUB_MODULE, |
| 32 | + useFactory, |
| 33 | + inject, |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + return { |
| 38 | + provide: PUBSUB_MODULE, |
| 39 | + inject: useExisting ? [useExisting] : useClass ? [useClass] : [], |
| 40 | + useFactory: (f: PubsubOptionsFactory) => f.createOptions(), |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +function createAsyncProviders(options: PubsubAsyncOptions): Provider[] { |
| 45 | + if (options.useExisting || options.useFactory) { |
| 46 | + return [createAsyncOptionsProvider(options)]; |
| 47 | + } |
| 48 | + return [ |
| 49 | + createAsyncOptionsProvider(options), |
| 50 | + { |
| 51 | + provide: options.useClass, |
| 52 | + useClass: options.useClass, |
| 53 | + inject: [options.inject ?? []], |
| 54 | + } as ClassProvider, |
| 55 | + ]; |
| 56 | +} |
| 57 | + |
| 58 | +@Global() |
| 59 | +@Module({}) |
| 60 | +export class PubsubModule { |
| 61 | + static forRoot(options: ClientConfig): DynamicModule { |
| 62 | + const provider = createProvider(options); |
| 63 | + return { |
| 64 | + module: PubsubModule, |
| 65 | + exports: [provider], |
| 66 | + providers: [provider], |
| 67 | + }; |
| 68 | + } |
| 69 | + |
| 70 | + static forRootAsync(options: PubsubAsyncOptions): DynamicModule { |
| 71 | + const provider: Provider<PubSub> = { |
| 72 | + inject: [PUBSUB_MODULE], |
| 73 | + provide: PUBSUB_TOKEN, |
| 74 | + useFactory: (options: ClientConfig) => getClient(options), |
| 75 | + }; |
| 76 | + |
| 77 | + return { |
| 78 | + exports: [provider], |
| 79 | + imports: options.imports, |
| 80 | + module: PubsubModule, |
| 81 | + providers: [...createAsyncProviders(options), provider], |
| 82 | + }; |
| 83 | + } |
| 84 | +} |
0 commit comments