@nestjs/common#Global TypeScript Examples

The following examples show how to use @nestjs/common#Global. 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: git.module.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Global()
@Module({
  imports: [
    ConfigModule,
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: ['.env.local', '.env']
    })
  ],
  providers: [GitService, GithubService, GitServiceFactory],
  exports: [GitService, GitServiceFactory, GithubService]
})
export class GitModule {}
Example #2
Source File: common.module.ts    From emutypekov with GNU General Public License v3.0 6 votes vote down vote up
/*
 * A module that contains commonly used libraries and services, such as file IO,
 * server configurations, and other server information.
 */

@Global()
@Module({
  providers: [CommonService],
  exports: [CommonService],
})
export class CommonModule {}
Example #3
Source File: mqtt.module.ts    From nest-mqtt with MIT License 6 votes vote down vote up
@Global()
@Module({
  imports: [DiscoveryModule],
  exports: [MqttService],
})
export class MqttModule {

  public static forRootAsync(options: MqttModuleAsyncOptions): DynamicModule {
    return {
      module: MqttModule,
      providers: [
        ...createOptionProviders(options),
        createLoggerProvider(options),
        createClientProvider(),
        MqttExplorer,
        MqttService,
      ],
    };
  }

  public static forRoot(options: MqttModuleOptions): DynamicModule {
    return {
      module: MqttModule,
      providers: [
        {
          provide: MQTT_OPTION_PROVIDER,
          useValue: options,
        },
        createLoggerProvider(options),
        createClientProvider(),
        MqttExplorer,
        MqttService,
      ],
    };
  }
}
Example #4
Source File: mikro-orm-middleware.module.ts    From nestjs with MIT License 6 votes vote down vote up
@Global()
@Module({})
export class MikroOrmMiddlewareModule {

  constructor(@Inject(MIKRO_ORM_MODULE_OPTIONS)
              private readonly options: MikroOrmMiddlewareModuleOptions) { }

  static forMiddleware(options?: MikroOrmMiddlewareModuleOptions) {
    // Work around due to nestjs not supporting the ability to register multiple types
    // https://github.com/nestjs/nest/issues/770
    // https://github.com/nestjs/nest/issues/4786#issuecomment-755032258 - workaround suggestion
    const inject = CONTEXT_NAMES.map(name => getMikroORMToken(name));
    return {
      module: MikroOrmMiddlewareModule,
      providers: [
        { provide: MIKRO_ORM_MODULE_OPTIONS, useValue: options || {} },
        {
          provide: 'MikroORMs',
          useFactory: (...args: MikroORM[]) => args,
          inject,
        },
      ],
    };
  }

  configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(MultipleMikroOrmMiddleware)
      .forRoutes({ path: forRoutesPath(this.options, consumer), method: RequestMethod.ALL });
  }

}
Example #5
Source File: async-hooks-module.ts    From nest-xray with MIT License 6 votes vote down vote up
@Global()
@Module({
  providers: [
    {
      provide: AsyncContext,
      useValue: AsyncContext.getInstance(),
    },
  ],
  exports: [AsyncContext],
})
export class AsyncHooksModule {}
Example #6
Source File: http-environment.module.ts    From nest-xray with MIT License 6 votes vote down vote up
// this module is global to ensure that middlewares are only called once
@Global()
@Module({ imports: [AsyncHooksModule] })
export class HttpEnvironmentModule implements NestModule {
  public configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AsyncHooksMiddleware)
      .forRoutes("/")
      .apply(HttpTracingMiddleware)
      .forRoutes("/");
  }
}
Example #7
Source File: tenancy-feature.module.ts    From nestjs-tenancy with MIT License 6 votes vote down vote up
@Global()
@Module({})
export class TenancyFeatureModule {

    static register(models: ModelDefinition[]): DynamicModule {
        const providers = createTenancyProviders(models);

        return {
            module: TenancyFeatureModule,
            providers,
            exports: providers,
        };
    }

}
Example #8
Source File: index.ts    From bank-server with MIT License 6 votes vote down vote up
@Global()
@Module({
  providers,
  imports: [
    HttpModule,
    JwtModule.registerAsync({
      useFactory: (configService: ConfigService) => ({
        privateKey: configService.get('JWT_SECRET_KEY'),
        // signOptions: {
        //   expiresIn: configService.get<number>('JWT_EXPIRATION_TIME'),
        // },
      }),
      inject: [ConfigService],
    }),
  ],
  exports: [...providers, HttpModule, JwtModule],
})
export class SharedModule {}
Example #9
Source File: InfrastructureModule.ts    From typescript-clean-architecture with MIT License 6 votes vote down vote up
@Global()
@Module({
  imports: [
    CqrsModule,
    TypeOrmModule.forRoot({
      name                     : 'default',
      type                     : 'postgres',
      host                     : DatabaseConfig.DB_HOST,
      port                     : DatabaseConfig.DB_PORT,
      username                 : DatabaseConfig.DB_USERNAME,
      password                 : DatabaseConfig.DB_PASSWORD,
      database                 : DatabaseConfig.DB_NAME,
      logging                  : DatabaseConfig.DB_LOG_ENABLE ? 'all' : false,
      logger                   : DatabaseConfig.DB_LOG_ENABLE ? TypeOrmLogger.new() : undefined,
      entities                 : [`${TypeOrmDirectory}/entity/**/*{.ts,.js}`],
      migrationsRun            : true,
      migrations               : [`${TypeOrmDirectory}/migration/**/*{.ts,.js}`],
      migrationsTransactionMode: 'all',
    })
  ],
  providers: providers,
  exports: [
    CoreDITokens.CommandBus,
    CoreDITokens.QueryBus,
    CoreDITokens.EventBus,
  ]
})
export class InfrastructureModule implements OnApplicationBootstrap {
  onApplicationBootstrap(): void {
    initializeTransactionalContext();
  }
}
Example #10
Source File: segmentAnalytics.module.ts    From amplication with Apache License 2.0 6 votes vote down vote up
@Global()
@Module({})
export class SegmentAnalyticsModule {
  /**
   *  public static register( ... )
   *  omitted here for brevity
   */

  public static registerAsync(
    options: SegmentAnalyticsAsyncOptions
  ): DynamicModule {
    return {
      module: SegmentAnalyticsModule,
      imports: [GoogleSecretsManagerModule],
      providers: [
        SegmentAnalyticsService,
        ...this.createConnectProviders(options)
      ],
      exports: [SegmentAnalyticsService]
    };
  }

  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 #11
Source File: twilio.module.ts    From twilio-voice-notification-app with Apache License 2.0 6 votes vote down vote up
@Global()
@Module({
  providers: [
    {
      provide: TwilioService,
      useValue: mockedTwilioService,
    },
  ],
  exports: [TwilioService],
})
export class TwilioModule {}
Example #12
Source File: auth.module.ts    From Cromwell with MIT License 6 votes vote down vote up
@Global()
@Module({
    imports: [
        JwtModule.register({
            signOptions: {
                algorithm: 'HS256'
            },
        }),
        RestApiModule,
    ],
    providers: [AuthService, JwtAuthGuard],
    exports: [AuthService],
})
export class AuthModule { }
Example #13
Source File: fcm.module.ts    From nestjs-fcm with MIT License 6 votes vote down vote up
@Global()
@Module({})
export class FcmModule {
  static forRoot(options: FcmOptions): DynamicModule {
    const optionsProvider: ValueProvider = {
      provide: FCM_OPTIONS,
      useValue: options,
    };
    const logger = options.logger ? options.logger : new Logger('FcmService');
    return {
      module: FcmModule,
      providers: [
        { provide: Logger, useValue: logger },
        FcmService,
        optionsProvider,
      ],
      exports: [FcmService],
    };
  }
}
Example #14
Source File: joi-pipe.module.ts    From nestjs-joi with MIT License 6 votes vote down vote up
@Global()
@Module({
  imports: [],
  controllers: [],
  providers: [
    {
      provide: APP_PIPE,
      useClass: JoiPipe,
    },
  ],
  exports: [],
})
export class JoiPipeModule {
  static forRoot(options: JoiPipeModuleOptions = {}): DynamicModule {
    const providers: Provider[] = [
      {
        provide: APP_PIPE,
        useClass: JoiPipe,
      },
    ];

    if (options.pipeOpts) {
      providers.push({
        provide: JOIPIPE_OPTIONS,
        useValue: options.pipeOpts,
      });
    }

    return {
      module: JoiPipeModule,
      global: true,
      providers,
    };
  }
}
Example #15
Source File: nestjs-integration.spec.ts    From nestjs-joi with MIT License 6 votes vote down vote up
@Global()
        @Module({
          providers: [
            {
              provide: JOIPIPE_OPTIONS,
              useValue: {
                usePipeValidationException: true,
              },
            },
          ],
          exports: [JOIPIPE_OPTIONS],
        })
        class OptionsModule {}
Example #16
Source File: gcloud-storage-core.module.ts    From nestjs-gcloud-storage with MIT License 5 votes vote down vote up
@Global()
@Module({
  providers: [...PROVIDERS],
  exports: [...PROVIDERS],
})
export class GCloudStorageCoreModule {
  static withConfig(options: GCloudStorageOptions): DynamicModule {
    const gcsModuleOptions = {
      provide: GCLOUD_STORAGE_MODULE_OPTIONS,
      useValue: options,
    };

    const gcsServiceProvider = {
      provide: GCloudStorageService,
      useFactory: (options: GCloudStorageOptions) => new GCloudStorageService(options),
      inject: [GCLOUD_STORAGE_MODULE_OPTIONS],
    };

    return {
      module: GCloudStorageCoreModule,
      providers: [gcsModuleOptions, GCloudMulterStorageService, gcsServiceProvider],
      exports: [...EXPORTS],
    };
  }

  static withConfigAsync(options: GCloudStorageAsyncOptions): DynamicModule {
    const gcsServiceProvider = {
      provide: GCloudStorageService,
      useFactory: (options: GCloudStorageOptions) => new GCloudStorageService(options),
      inject: [GCLOUD_STORAGE_MODULE_OPTIONS],
    };

    return {
      module: GCloudStorageCoreModule,
      imports: options.imports,
      providers: [
        {
          provide: GCLOUD_STORAGE_MODULE_OPTIONS,
          useFactory: options.useFactory,
          inject: options.inject || [],
        },
        GCloudMulterStorageService,
        gcsServiceProvider,
      ],
      exports: [...EXPORTS],
    };
  }
}
Example #17
Source File: kafka.module.ts    From nestjs-kafka with The Unlicense 5 votes vote down vote up
@Global()
@Module({})
export class KafkaModule {
  static register(options: KafkaModuleOption[]): DynamicModule {
    const clients = (options || []).map((item) => ({
      provide: item.name,
      useValue: new KafkaService(item.options),
    }));

    return {
      module: KafkaModule,
      providers: clients,
      exports: clients,
    };
  }

  public static registerAsync(
    consumers: string[],
    connectOptions: KafkaModuleOptionsAsync,
  ): DynamicModule {
    const clients = [];
    for (const consumer of consumers) {
      clients.push({
        provide: consumer,
        useFactory: async (
          kafkaModuleOptionsProvider: KafkaModuleOptionsProvider,
        ) => {
          return new KafkaService(
            kafkaModuleOptionsProvider.getOptionsByName(consumer),
          );
        },
        inject: [KafkaModuleOptionsProvider],
      });
    }

    const createKafkaModuleOptionsProvider = this.createKafkaModuleOptionsProvider(connectOptions);

    return {
      module: KafkaModule,
      imports: connectOptions.imports || [],
      providers: [
        createKafkaModuleOptionsProvider,
        KafkaModuleOptionsProvider,
        ...clients,
      ],
      exports: [
        createKafkaModuleOptionsProvider,
        ...clients,
      ],
    };
  }

  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 #18
Source File: test.module.ts    From pebula-node with MIT License 5 votes vote down vote up
@Global()
@Module({
  providers: [ ConfigService, MessageStorage ],
  exports: [ ConfigService, MessageStorage ],
})
export class NestBusSharedModule {

}
Example #19
Source File: twilio.module.ts    From twilio-voice-notification-app with Apache License 2.0 5 votes vote down vote up
@Global()
@Module({
  providers: [TwilioService],
  exports: [TwilioService],
})
export class TwilioModule {}
Example #20
Source File: dynamoose-core.module.ts    From nestjs-dynamoose with MIT License 5 votes vote down vote up
@Global()
@Module({})
export class DynamooseCoreModule {
  static forRoot(options: DynamooseModuleOptions = {}): DynamicModule {
    const initialProvider = {
      provide: DYNAMOOSE_INITIALIZATION,
      useFactory: () => initialization(options),
    };
    return {
      module: DynamooseCoreModule,
      providers: [initialProvider],
      exports: [initialProvider],
    };
  }

  static forRootAsync(options: DynamooseModuleAsyncOptions): DynamicModule {
    const initialProvider = {
      provide: DYNAMOOSE_INITIALIZATION,
      useFactory: (dynamoooseModuleOptions: DynamooseModuleOptions) =>
        initialization(dynamoooseModuleOptions),
      inject: [DYNAMOOSE_MODULE_OPTIONS],
    };

    const asyncProviders = this.createAsyncProviders(options);
    return {
      module: DynamooseCoreModule,
      imports: options.imports,
      providers: [...asyncProviders, initialProvider],
      exports: [initialProvider],
    };
  }

  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,
      },
    ];
  }

  private static createAsyncOptionsProvider(
    options: DynamooseModuleAsyncOptions,
  ): Provider {
    if (options.useFactory) {
      return {
        provide: DYNAMOOSE_MODULE_OPTIONS,
        useFactory: options.useFactory,
        inject: options.inject || [],
      };
    }

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

    return {
      provide: DYNAMOOSE_MODULE_OPTIONS,
      useFactory: async (optionsFactory: DynamooseOptionsFactory) =>
        await optionsFactory.createDynamooseOptions(),
      inject,
    };
  }
}
Example #21
Source File: firebase-admin-core.module.ts    From nestjs-firebase-admin with MIT License 5 votes vote down vote up
@Global()
@Module({})
export class FirebaseAdminCoreModule {
  static forRoot(options: FirebaseAdminModuleOptions): DynamicModule {
    const firebaseAdminModuleOptions = {
      provide: FIREBASE_ADMIN_MODULE_OPTIONS,
      useValue: options,
    };

    const app = admin.apps.length === 0 ? admin.initializeApp(options) : admin.apps[0];

    const providers = this.createProviders(app);

    return {
      module: FirebaseAdminCoreModule,
      providers: [firebaseAdminModuleOptions, ...providers],
      exports: [...EXPORTS],
    };
  }

  private static createProviders(app: admin.app.App): Provider<any>[] {
    return PROVIDERS.map<Provider>((ProviderService) => ({
      provide: ProviderService,
      useFactory: () => new ProviderService(app),
    }));
  }

  static forRootAsync(options: FirebaseAdminModuleAsyncOptions): DynamicModule {
    const firebaseAdminModuleOptions = {
      provide: FIREBASE_ADMIN_MODULE_OPTIONS,
      useFactory: options.useFactory,
      inject: options.inject || [],
    };

    const providers = this.createAsyncProviders();

    return {
      module: FirebaseAdminCoreModule,
      imports: options.imports,
      providers: [firebaseAdminModuleOptions, ...providers],
      exports: [...EXPORTS],
    };
  }

  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 #22
Source File: consul.module.ts    From nestjs-consul with MIT License 5 votes vote down vote up
@Global()
@Module({})
export class ConsulModule {
	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],
		};
	}

	static forRootAsync<T>(options: IConsulAsyncConfig<T>): DynamicModule {
		const consulServiceProvider = this.createAsyncOptionsProvider<T>(options);
		return {
			module: ConsulModule,
			imports: options.imports,
			providers: [consulServiceProvider],
			exports:[consulServiceProvider]
		};
	}

	private static createAsyncOptionsProvider<T>(
		options: IConsulAsyncConfig<T>,
	): Provider {
		return {
			provide: ConsulService,
			useFactory: async (...args: any[]) => {
				const config = await options.useFactory(...args);
				const consulService = new ConsulService<T>(config, new HttpService());
				if (config.keys) {
					await consulService.update();
				}
				return consulService;
			},
			inject: options.inject || [],
		};
	}
}
Example #23
Source File: mercurius-core.module.ts    From nestjs-mercurius with MIT License 5 votes vote down vote up
@Global()
@Module({
  providers: [PubSubHost],
  exports: [PubSubHost],
})
export class MercuriusCoreModule {}
Example #24
Source File: config.module.ts    From nest-react with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Global()
@Module({
  providers: [ConfigService],
  exports: [ConfigService],
})
export class ConfigModule {}
Example #25
Source File: unit-of-work.module.ts    From domain-driven-hexagon with MIT License 5 votes vote down vote up
@Global()
@Module({
  imports: [],
  providers: [unitOfWorkSingletonProvider],
  exports: [UnitOfWork],
})
export class UnitOfWorkModule {}
Example #26
Source File: cache.module.ts    From runebot with MIT License 5 votes vote down vote up
@Global()
@Module({
  imports: [AppConfigModule],
  providers: [CacheService],
  exports: [CacheService],
})
export class CacheModule {}
Example #27
Source File: module.ts    From nestjs-keycloak-admin with MIT License 5 votes vote down vote up
@Global()
@Module({
  providers: [KeycloakService],
  exports: [KeycloakService],
})
export class KeycloakModule {
  public static register(options: KeycloakModuleOptions): DynamicModule {
    const provider = this.getOptionsProvider(options)
    return {
      module: KeycloakModule,
      providers: [provider, this.keycloakProvider],
      exports: [provider, this.keycloakProvider],
    }
  }

  public static registerAsync(options: KeycloakModuleAsyncOptions): DynamicModule {
    const customOptions = this.getCustomOptions(options)

    return {
      module: KeycloakModule,
      imports: options.imports || [],
      providers: [customOptions, this.keycloakProvider],
      exports: [customOptions, this.keycloakProvider],
    }
  }

  private static getCustomOptions(options: KeycloakModuleAsyncOptions): Provider {
    return {
      provide: KEYCLOAK_ADMIN_OPTIONS,
      useFactory: options.useFactory,
      inject: options.inject || [],
    }
  }

  private static keycloakProvider: Provider = {
    provide: KeycloakService,
    useFactory: async (options: KeycloakModuleOptions) => {
      const client = new KeycloakService(options)
      await client.initialize()
      return client
    },
    inject: [KEYCLOAK_ADMIN_OPTIONS],
  }

  private static getOptionsProvider(options: KeycloakModuleOptions): Provider {
    return {
      provide: KEYCLOAK_ADMIN_OPTIONS,
      useValue: options,
    }
  }
}
Example #28
Source File: module.ts    From test with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Global()
@Module({
  imports: [LoggerModule, feature.module, TypeOrmModule.forRoot(config)],
  providers: [...feature.providers, UserStoreRepository],
  exports: [...feature.exports, UserStoreRepository],
})
export class PersistenceModule {}
Example #29
Source File: shared.module.ts    From codeclannigeria-backend with MIT License 5 votes vote down vote up
@Global()
@Module({
  imports: [],
  providers: [],
  exports: []
})
export class SharedModule {}