@nestjs/common#Provider TypeScript Examples

The following examples show how to use @nestjs/common#Provider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: firebase-admin-core.module.ts    From nestjs-firebase-admin with MIT License 6 votes vote down vote up
private static createAsyncProviders(): Provider<any>[] {
    return PROVIDERS.map<Provider>((ProviderService) => ({
      provide: ProviderService,
      useFactory: (options: FirebaseAdminModuleOptions) => {
        const app = admin.apps.length === 0 ? admin.initializeApp(options) : admin.apps[0];
        return new ProviderService(app);
      },
      inject: [FIREBASE_ADMIN_MODULE_OPTIONS],
    }));
  }
Example #2
Source File: consul.module.ts    From nestjs-consul with MIT License 6 votes vote down vote up
static forRoot<T>(config: IConsulConfig<T>): DynamicModule {
		const consulServiceProvider: Provider = {
			provide: ConsulService,
			useFactory: async () => {
				const consulService = new ConsulService<T>(config, new HttpService());
				if (config.keys) {
					await consulService.update();
				}
				return consulService;
			},
		};
		return {
			module: ConsulModule,
			providers: [consulServiceProvider],
			exports: [consulServiceProvider],
		};
	}
Example #3
Source File: mercurius-gateway.module.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
private static createAsyncProviders(
    options: MercuriusGatewayModuleAsyncOptions,
  ): Provider[] {
    if (options.useExisting || options.useFactory) {
      return [this.createAsyncOptionsProvider(options)];
    }

    return [
      this.createAsyncOptionsProvider(options),
      {
        provide: options.useClass,
        useClass: options.useClass,
      },
    ];
  }
Example #4
Source File: mailgun.module.ts    From nestjs-mailgun with MIT License 6 votes vote down vote up
private static createAsyncProviders(
    options: OptionsAsync,
  ): Provider {
    return {
      provide: MAILGUN_CONFIGURATION,
      useFactory: options.useFactory,
      inject: options.inject || [],
    };
  }
Example #5
Source File: event-store.module.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
private static async getEventStoreConnector(
    config: EventStoreConnectionConfig,
  ): Promise<Provider> {
    const eventStoreConnector: Client = EventStoreDBClient.connectionString(
      (config as EventStoreConnectionConfig).connectionSettings
        .connectionString,
    );

    return {
      provide: EVENT_STORE_CONNECTOR,
      useValue: eventStoreConnector,
    };
  }
Example #6
Source File: wallet.providers.ts    From domain-driven-hexagon with MIT License 6 votes vote down vote up
createWalletWhenUserIsCreatedProvider: Provider = {
  provide: CreateWalletWhenUserIsCreatedDomainEventHandler,
  useFactory: (
    unitOfWork: UnitOfWork,
  ): CreateWalletWhenUserIsCreatedDomainEventHandler => {
    const eventHandler = new CreateWalletWhenUserIsCreatedDomainEventHandler(
      unitOfWork,
    );
    eventHandler.listen();
    return eventHandler;
  },
  inject: [UnitOfWork],
}
Example #7
Source File: serve-static.provider.ts    From adminjs-nestjs with MIT License 6 votes vote down vote up
serveStaticProvider: Provider = {
  provide: AbstractLoader,
  useFactory: (httpAdapterHost: HttpAdapterHost) => {
    if (!httpAdapterHost || !httpAdapterHost.httpAdapter) {
      return new NoopLoader();
    }
    const httpAdapter = httpAdapterHost.httpAdapter;
    if (
      httpAdapter &&
        httpAdapter.constructor &&
        httpAdapter.constructor.name === 'FastifyAdapter'
    ) {
      // Not handled right now
      return new NoopLoader();
    }
    
    return new ExpressLoader();
  },
  inject: [HttpAdapterHost],
}
Example #8
Source File: segmentAnalytics.module.ts    From amplication with Apache License 2.0 6 votes vote down vote up
private static createConnectProviders(
    options: SegmentAnalyticsAsyncOptions
  ): Provider[] {
    return [
      {
        provide: 'SEGMENT_ANALYTICS_OPTIONS',
        useFactory: async (optionsFactory: SegmentAnalyticsOptionsFactory) =>
          await optionsFactory.createSegmentAnalyticsOptions(),
        inject: [options.useClass]
      },
      {
        provide: options.useClass,
        useClass: options.useClass
      }
    ];
  }
Example #9
Source File: module.ts    From nestjs-keycloak-admin with MIT License 6 votes vote down vote up
private static keycloakProvider: Provider = {
    provide: KeycloakService,
    useFactory: async (options: KeycloakModuleOptions) => {
      const client = new KeycloakService(options)
      await client.initialize()
      return client
    },
    inject: [KEYCLOAK_ADMIN_OPTIONS],
  }
Example #10
Source File: http.module.ts    From nestjs-http-promise with MIT License 6 votes vote down vote up
private static createAsyncProviders(
      options: HttpModuleAsyncOptions,
  ): Provider[] {
    if (options.useExisting || options.useFactory) {
      return [this.createAsyncOptionsProvider(options)];
    }

    const providers = [
      this.createAsyncOptionsProvider(options)
    ];

    if(options.useClass)
      providers.push({
        provide: options.useClass,
        useClass: options.useClass,
      })

    return providers;
  }
Example #11
Source File: database.providers.ts    From nestjs-rest-microservices with MIT License 6 votes vote down vote up
DatabaseProvider: Provider = {
  provide: 'SEQUELIZE',
  useFactory: async (logger: PinoLogger) => {
    logger.setContext('Sequelize')

    const db: Sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, {
      dialect: 'postgres',
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT || '5432', 10),
      logging: logger.info.bind(logger),
      benchmark: true,
      retry: {
        max: 3
      }
    })

    db.addModels([Comment])

    await db.sync()

    return db
  },
  inject: [PinoLogger]
}
Example #12
Source File: google-recaptcha.module.ts    From google-recaptcha with MIT License 6 votes vote down vote up
static forRoot(options: GoogleRecaptchaModuleOptions): DynamicModule {
        const providers: Provider[] = [
            GoogleRecaptchaGuard,
            GoogleRecaptchaValidator,
            RecaptchaRequestResolver,
            {
                provide: RECAPTCHA_OPTIONS,
                useValue: options,
            },
        ];

        const httpModule = this.resolveHttpModule();

        const internalProviders: Provider[] = [
            Reflector,
            {
                provide: RECAPTCHA_HTTP_SERVICE,
                useFactory: (axiosInstance: axios.AxiosInstance) => new httpModule.HttpService(axiosInstance),
                inject: [
                    RECAPTCHA_AXIOS_INSTANCE,
                ],
            },
            {
                provide: RECAPTCHA_AXIOS_INSTANCE,
                useFactory: () => axios.default.create(this.transformAxiosConfig(options.axiosConfig)),
            },
        ];

        return {
            global: true,
            module: GoogleRecaptchaModule,
            imports: [
                httpModule.HttpModule,
            ],
            providers: providers.concat(internalProviders),
            exports: providers,
        }
    }
Example #13
Source File: nestjs-form-data.module.ts    From nestjs-form-data with MIT License 6 votes vote down vote up
private static createAsyncProviders(options: NestjsFormDataAsyncOptions): Provider[] {

    if (options.useExisting || options.useFactory) {
      return [this.createAsyncOptionsProvider(options)];
    }

    return [
      this.createAsyncOptionsProvider(options),
      {
        provide: options.useClass,
        useClass: options.useClass,
      },
    ];
  }
Example #14
Source File: tracing.module.ts    From nestjs-jaeger-tracing with MIT License 6 votes vote down vote up
static forRoot(options: TracingModuleOptions): DynamicModule {
    const providers: Provider[] = [];
    TracingModule.tracerProvider = TracerProvider.getInstance(options);
    TracingModule.tracer = TracingModule.tracerProvider.getTracer();
    const optionsProvider: Provider<TracingModuleOptions> = {
      provide: TRACING_MODULE_OPTIONS,
      useValue: options,
    };
    const tracerProvider: Provider = {
      provide: TRACER,
      useValue: TracingModule.tracer,
    };
    const tracerProviderFactory: Provider = {
      provide: TRACER_PROVIDER,
      useValue: TracingModule.tracerProvider,
    };
    providers.push(optionsProvider);
    providers.push(tracerProvider);
    providers.push(tracerProviderFactory);
    return {
      module: TracingModule,
      providers: [
        ...providers,
        {
          provide: APP_INTERCEPTOR,
          useClass: TracingInterceptor,
        },
      ],
      exports: [...providers],
    };
  }
Example #15
Source File: seeder.ts    From nestjs-seeder with MIT License 6 votes vote down vote up
seeder = (options: SeederOptions): SeederRunner => {
  return {
    run(seeders: Provider<Seeder>[]): void {
      bootstrap({
        ...options,
        seeders,
      });
    },
  };
}
Example #16
Source File: bull.module.ts    From nestjs-bullmq with MIT License 6 votes vote down vote up
/**
   * Registers a globally available configuration for all queues
   * or using a specified "configKey" (if passed).
   *
   * @param keyOrConfig a key under which the configuration should be available or a bull configuration object
   * @param bullConfig bull configuration object
   */
  static forRoot(
    keyOrConfig: string | Bull.QueueOptions,
    bullConfig?: Bull.QueueOptions,
  ): DynamicModule {
    const [configKey, sharedBullConfig] =
      typeof keyOrConfig === 'string'
        ? [keyOrConfig, bullConfig]
        : [undefined, keyOrConfig];

    const sharedBullConfigProvider: Provider = {
      provide: getSharedConfigToken(configKey),
      useValue: sharedBullConfig,
    };

    return {
      global: true,
      module: BullModule,
      providers: [sharedBullConfigProvider],
      exports: [sharedBullConfigProvider],
    };
  }
Example #17
Source File: keycloak-connect.module.ts    From nest-keycloak-connect with MIT License 6 votes vote down vote up
private static createAsyncProviders(
    options: KeycloakConnectModuleAsyncOptions,
  ): Provider[] {
    const reqProviders = [
      this.createAsyncOptionsProvider(options),
      loggerProvider,
      keycloakProvider,
      KeycloakMultiTenantService,
    ];

    if (options.useExisting || options.useFactory) {
      return reqProviders;
    }

    return [
      ...reqProviders,
      {
        provide: options.useClass,
        useClass: options.useClass,
      },
    ];
  }
Example #18
Source File: dynamoose-core.module.ts    From nestjs-dynamoose with MIT License 6 votes vote down vote up
private static createAsyncProviders(
    options: DynamooseModuleAsyncOptions,
  ): Provider[] {
    if (options.useExisting || options.useFactory) {
      return [this.createAsyncOptionsProvider(options)];
    }
    const useClass = options.useClass as Type<DynamooseOptionsFactory>;
    return [
      this.createAsyncOptionsProvider(options),
      {
        provide: useClass,
        useClass,
      },
    ];
  }
Example #19
Source File: client.provider.ts    From nest-mqtt with MIT License 6 votes vote down vote up
export function createClientProvider(): Provider {
  return {
    provide: MQTT_CLIENT_INSTANCE,
    useFactory: (options: MqttModuleOptions, logger: Logger) => {
      const client = connect(options);

      client.on('connect', () => {
        logger.log('MQTT connected');
        // console.log(packet);
      });

      client.on('disconnect', packet => {
        logger.log('MQTT disconnected');
      });

      client.on('error', error => {
      });

      client.on('reconnect', () => {
        logger.log('MQTT reconnecting');
      });

      client.on('close', error => {
        logger.log('MQTT closed');
      });

      client.on('offline', () => {
        logger.log('MQTT offline');
      });

      return client;
    },
    inject: [MQTT_OPTION_PROVIDER, MQTT_LOGGER_PROVIDER],
  };
}
Example #20
Source File: mikro-orm.providers.ts    From nestjs with MIT License 6 votes vote down vote up
export function createMikroOrmProvider(contextName?: string): Provider {
  return {
    provide: contextName ? getMikroORMToken(contextName) : MikroORM,
    useFactory: async (options?: MikroOrmModuleOptions) => {
      if (options?.autoLoadEntities) {
        options.entities = [...(options.entities || []), ...MikroOrmEntitiesStorage.getEntities(contextName)];
        options.entitiesTs = [...(options.entitiesTs || []), ...MikroOrmEntitiesStorage.getEntities(contextName)];
        delete options.autoLoadEntities;
      }

      MikroOrmEntitiesStorage.clear(contextName);

      if (!options || Object.keys(options).length === 0) {
        const config = await ConfigurationLoader.getConfiguration();
        config.set('logger', logger.log.bind(logger));
        options = config as unknown as MikroOrmModuleOptions;
      }

      return MikroORM.init(options);
    },
    inject: [MIKRO_ORM_MODULE_OPTIONS],
  };
}
Example #21
Source File: tenancy-core.module.ts    From nestjs-tenancy with MIT License 6 votes vote down vote up
/**
     * Create connection map provider
     *
     * @private
     * @static
     * @returns {Provider}
     * @memberof TenancyCoreModule
     */
    private static createConnectionMapProvider(): Provider {
        return {
            provide: CONNECTION_MAP,
            useFactory: (): ConnectionMap => new Map(),
        }
    }
Example #22
Source File: redis.core-module.ts    From ioredis with MIT License 6 votes vote down vote up
/* forRoot */
  static forRoot(options: RedisModuleOptions, connection?: string): DynamicModule {

    const redisOptionsProvider: Provider = {
      provide: getRedisOptionsToken(connection),
      useValue: options,
    };

    const redisConnectionProvider: Provider = {
      provide: getRedisConnectionToken(connection),
      useValue: createRedisConnection(options),
    };

    return {
      module: RedisCoreModule,
      providers: [
        redisOptionsProvider,
        redisConnectionProvider,
      ],
      exports: [
        redisOptionsProvider,
        redisConnectionProvider,
      ],
    };
  }
Example #23
Source File: pact-consumer-core.module.ts    From nestjs-pact with MIT License 6 votes vote down vote up
private static createAsyncProviders(options: PactConsumerModuleAsyncOptions): Provider[] {
    if (options.useExisting || options.useFactory) {
      return this.createAsyncOptionsProviders(options);
    }

    const { useClass } = options;

    return [
      ...this.createAsyncOptionsProviders(options),
      {
        provide: useClass,
        useClass,
      },
    ];
  }
Example #24
Source File: InfrastructureModule.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
providers: Provider[] = [
  {
    provide : APP_FILTER,
    useClass: NestHttpExceptionFilter,
  },
  {
    provide: CoreDITokens.CommandBus,
    useClass: NestCommandBusAdapter,
  },
  {
    provide: CoreDITokens.QueryBus,
    useClass: NestQueryBusAdapter,
  },
  {
    provide: CoreDITokens.EventBus,
    useClass: NestEventBusAdapter,
  }
]
Example #25
Source File: kafka.module.ts    From nestjs-kafka with The Unlicense 6 votes vote down vote up
private static createKafkaModuleOptionsProvider(
    options: KafkaModuleOptionsAsync,
  ): Provider {
    if (options.useFactory) {
      return {
        provide: KAFKA_MODULE_OPTIONS,
        useFactory: options.useFactory,
        inject: options.inject || [],
      };
    }
    return {
      provide: KAFKA_MODULE_OPTIONS,
      useFactory: async (optionsFactory: KafkaOptionsFactory) =>
        await optionsFactory.creatKafkaModuleOptions(),
      inject: [options.useExisting || options.useClass],
    };
  }
Example #26
Source File: service-bus.module.ts    From pebula-node with MIT License 6 votes vote down vote up
function normalizeProvider(provider: Omit<Exclude<Provider, Type<any>>, 'provide'> | Type<any>): Provider {
  if (typeof provider === 'function') {
    provider = { useClass: provider };
  }
  return {
    ...(provider as Exclude<Provider, Type<any>>),
    provide: SB_META_HELPER_FACTORY_TOKEN,
  };
}
Example #27
Source File: module.ts    From nest-notifications with MIT License 6 votes vote down vote up
private static createStorageOptionsProvider(
    options: NotificationAsyncOptions,
  ): Provider {
    if (options.useFactory) {
      return {
        provide: NOTIFICATION_OPTIONS,
        useFactory: options.useFactory,
        inject: options.inject || [],
      };
    }

    const inject = [
      (options.useClass || options.useExisting) as Type<NotificationOptions>,
    ];

    return {
      provide: NOTIFICATION_OPTIONS,
      useFactory: async (optionsFactory: NotificationAsyncOptionsFactory) =>
        await optionsFactory.createNotificationOptions(),
      inject,
    };
  }
Example #28
Source File: sqs.module.ts    From nestjs-sqs with MIT License 6 votes vote down vote up
public static register(options: SqsOptions): DynamicModule {
    const sqsOptions: Provider = {
      provide: SQS_OPTIONS,
      useValue: options,
    };
    const sqsProvider: Provider = {
      provide: SqsService,
      useFactory: (sqsOptions: SqsOptions, discover: DiscoveryService) => new SqsService(options, discover),
      inject: [SQS_OPTIONS, DiscoveryService],
    };

    return {
      global: true,
      module: SqsModule,
      imports: [
        DiscoveryModule,
      ],
      providers: [
        sqsOptions,
        sqsProvider,
      ],
      exports: [
        sqsProvider,
      ],
    };
  }
Example #29
Source File: oauth2-core.module.ts    From nestjs-oauth2-server-module with MIT License 6 votes vote down vote up
private static createAsyncOptionsProvider(options: Oauth2AsyncOptionsInterface): Provider {
        if (options.useFactory) {
            return {
                provide: OAUTH2_SERVER_OPTIONS,
                useFactory: options.useFactory,
                inject: options.inject || [],
            };
        }

        return {
            provide: OAUTH2_SERVER_OPTIONS,
            useFactory: async (optionsFactory: Oauth2OptionsFactoryInterface) => {
                return optionsFactory.createOauth2Options();
            },
            inject: [options.useExisting || options.useClass],
        };
    }