All files / lib sendgrid-core.module.ts

100% Statements 22/22
90% Branches 9/10
100% Functions 7/7
100% Lines 20/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 712x   2x 2x 2x       2x   5x   5x               2x     2x     2x                     2x 1x   1x 1x                       2x 1x           1x     1x   1x 1x        
import { Global, Module, DynamicModule, Provider, Type } from '@nestjs/common';
import { SendGridModuleOptions, SendGridModuleAsyncOptions, SendGridOptionsFactory } from './interfaces';
import { createSendGridProviders } from './providers';
import { SENDGRID_MODULE_OPTIONS, SENDGRID_TOKEN } from './common/sendgrid.constants';
import { createSendGridClient } from './common/sendgrid.util';
 
@Global()
@Module({})
export class SendGridCoreModule {
    public static forRoot(options: SendGridModuleOptions): DynamicModule {
        const provider = createSendGridProviders(options);
 
        return {
            exports: [provider,],
            module: SendGridCoreModule,
            providers: [provider]
        };
    }
 
    public static forRootAsync(options: SendGridModuleAsyncOptions): DynamicModule {
        const provider: Provider = {
            inject: [SENDGRID_MODULE_OPTIONS],
            provide: SENDGRID_TOKEN,
            useFactory: (options: SendGridModuleOptions) => createSendGridClient(options),
        };
 
        return {
            exports: [provider],
            imports: options.imports,
            module: SendGridCoreModule,
            providers: [...this.createAsyncProviders(options), provider]
        };
    }
 
    private static createAsyncProviders(
        options: SendGridModuleAsyncOptions,
      ): Provider[] {
        if (options.useExisting || options.useFactory) {
          return [this.createAsyncOptionsProvider(options)];
        }
        const useClass = options.useClass as Type<SendGridOptionsFactory>;
        return [
          this.createAsyncOptionsProvider(options),
          {
            provide: useClass,
            useClass,
          },
        ];
      }
    
      private static createAsyncOptionsProvider(
        options: SendGridModuleAsyncOptions,
      ): Provider {
        if (options.useFactory) {
          return {
            inject: options.inject || [],
            provide: SENDGRID_MODULE_OPTIONS,
            useFactory: options.useFactory,
          };
        }
        const inject = [
          (options.useClass || options.useExisting) as Type<SendGridOptionsFactory>,
        ];
        return {
          provide: SENDGRID_MODULE_OPTIONS,
          useFactory: async (optionsFactory: SendGridOptionsFactory) =>
            await optionsFactory.createSendGridOptions(),
          inject,
        };
      }
}