@nestjs/config#ConfigService TypeScript Examples

The following examples show how to use @nestjs/config#ConfigService. 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: user.service.ts    From 42_checkIn with GNU General Public License v3.0 7 votes vote down vote up
constructor(
    private readonly authService: AuthService,
    private readonly userRepository: UserRepository,
    private readonly cardRepository: CardRepository,
    @Inject(forwardRef(() => CardService))
    private readonly cardServcie: CardService,
    private readonly logService: LogService,
    private readonly logger: MyLogger,
    private readonly configService: ConfigService,
    private readonly httpService: HttpService,
    private readonly waitingService: WaitingService,
    private readonly waitingRepository: WaitingRepository,
  ) {}
Example #2
Source File: _main.ts    From nest-js-boilerplate with MIT License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalPipes(new ValidationPipe({
    exceptionFactory: (errors: ValidationError[]) => new ValidationExceptions(errors),
  }));
  app.useGlobalFilters(new AllExceptionsFilter());

  const configService = app.get(ConfigService);
  const port = configService.get<number>('SERVER_POR') || 3000;

  const options = new DocumentBuilder()
    .setTitle('Api v1')
    .setDescription('The boilerplate API for nestjs devs')
    .setVersion('1.0')
    .addBearerAuth({ in: 'header', type: 'http' })
    .build();
  const document = SwaggerModule.createDocument(app, options);

  SwaggerModule.setup('api', app, document);

  await app.listen(port, async () => {
    console.log(`The server is running on ${port} port: http://localhost:${port}/api`);
  });
}
Example #3
Source File: config.module.ts    From runebot with MIT License 6 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
    }),
  ],
  providers: [ConfigService, AppConfigService],
  exports: [ConfigService, AppConfigService],
})
export class AppConfigModule {}
Example #4
Source File: secretsManager.service.base.spec.ts    From amplication with Apache License 2.0 6 votes vote down vote up
describe("Testing the secrets manager base class", () => {
  const SECRET_KEY = "SECRET_KEY";
  const SECRET_VALUE = "SECRET_VALUE";
  const configService = mock<ConfigService>();
  const secretsManagerServiceBase = new SecretsManagerServiceBase(
    configService
  );
  beforeEach(() => {
    configService.get.mockClear();
  });
  it("should return value from env", async () => {
    //ARRANGE
    configService.get.mockReturnValue(SECRET_VALUE);
    //ACT
    const result = await secretsManagerServiceBase.getSecret(SECRET_KEY);
    //ASSERT
    expect(result).toBe(SECRET_VALUE);
  });
  it("should return null for unknown keys", async () => {
    //ARRANGE
    configService.get.mockReturnValue(undefined);
    //ACT
    const result = await secretsManagerServiceBase.getSecret(SECRET_KEY);
    //ASSERT
    expect(result).toBeNull();
  });
  it("should throw error if dont get key", () => {
    //@ts-ignore
    return expect(secretsManagerServiceBase.getSecret()).rejects.toThrow();
  });
  it("should throw an exeption if getting null key", () => {
    //@ts-ignore
    return expect(secretsManagerServiceBase.getSecret(null)).rejects.toThrow();
  });
});
Example #5
Source File: app.module.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configurations],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('database.host'),
        port: configService.get('database.port'),
        username: configService.get('database.user'),
        password: configService.get('database.password'),
        database: configService.get('database.name'),
        autoLoadEntities: true,
        synchronize: true,
        entities: ['dist/**/*.entity.js'],
      }),
      inject: [ConfigService],
    }),
    ConsumerModule,
    ProgramsModule,
    MessagesModule,
    MetadataModule,
    HealthcheckModule,
  ],
  controllers: [HealthcheckController],
})
export class AppModule {}
Example #6
Source File: database.module.ts    From coronatest with GNU Affero General Public License v3.0 6 votes vote down vote up
@Module({
    imports: [
        SequelizeModule.forRootAsync({
            useFactory: (configService: ConfigService) => ({
                dialect: 'postgres',
                host: configService.get<string>('postgres.host'),
                port: +configService.get('postgres.port'),
                username: configService.get<string>('postgres.username'),
                password: configService.get<string>('postgres.password'),
                database: configService.get<string>('postgres.database'),
                logging: false,
                autoLoadModels: true,
                synchronize: true,
                retryAttempts: 3,
                define: {
                    paranoid: true,
                    underscored: true
                },
                // sync: {
                //     force: true
                // }
            }),
            inject: [ConfigService]
        })
    ],
    controllers: [],
    providers: [],
    exports: []
})
export class DatabaseModule {}
Example #7
Source File: main.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: false,
  })

  app.useLogger(new AppLogger())
  app.use(RequestIdMiddleware)
  app.enableCors()

  const configService = app.get(ConfigService)
  const backendAppPort = configService.get('BACKEND_APP_PORT')

  const options = new DocumentBuilder()
    .setTitle('mamori-i-japan-api')
    .setDescription('Swagger UI for mamori-i-japan-api API')
    .setVersion('1.0')
    .addBearerAuth()
    .build()
  const document = SwaggerModule.createDocument(app, options)
  SwaggerModule.setup('swagger', app, document)

  await app.listen(backendAppPort)
}
Example #8
Source File: auth.module.ts    From nestjs-starter-rest-api with MIT License 6 votes vote down vote up
@Module({
  imports: [
    SharedModule,
    PassportModule.register({ defaultStrategy: STRATEGY_JWT_AUTH }),
    JwtModule.registerAsync({
      imports: [SharedModule],
      useFactory: async (configService: ConfigService) => ({
        publicKey: configService.get<string>('jwt.publicKey'),
        privateKey: configService.get<string>('jwt.privateKey'),
        signOptions: {
          algorithm: 'RS256',
        },
      }),
      inject: [ConfigService],
    }),
    UserModule,
  ],
  controllers: [AuthController],
  providers: [AuthService, LocalStrategy, JwtAuthStrategy, JwtRefreshStrategy],
})
export class AuthModule {}
Example #9
Source File: jwt.strategy.ts    From api with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(
    configService: ConfigService,
    private readonly userService: UserService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<string>('SECRET_KEY'),
    });
  }
Example #10
Source File: main.ts    From bank-server with MIT License 6 votes vote down vote up
async function bootstrap(): Promise<void> {
  initializeTransactionalContext();
  patchTypeORMRepositoryWithBaseRepository();

  const app = await NestFactory.create<NestExpressApplication>(
    AppModule,
    new ExpressAdapter(),
    { cors: true },
  );

  app.enable('trust proxy');
  app.use(helmet());
  app.use(RateLimit({ windowMs: 15 * 60 * 1000, max: 200 }));
  app.use(compression());
  app.use(morgan('combined'));
  app.setGlobalPrefix('bank');

  const reflector = app.get(Reflector);

  app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector));
  app.useGlobalFilters(
    new HttpExceptionFilter(reflector),
    new QueryFailedFilter(reflector),
  );
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      dismissDefaultMessages: true,
      validationError: { target: false },
    }),
  );

  setupSwagger(app);

  const configService = app.get(ConfigService);
  await app.listen(configService.get('PORT'));
}
Example #11
Source File: database.module.ts    From nestjs-starter with MIT License 6 votes vote down vote up
@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      useFactory: (configService: ConfigService) => configService.get<TypeOrmModuleOptions>(CONFIG_DB_CONFIG),
      inject: [ConfigService],
    }),
  ],
})
export class DatabaseModule {}
Example #12
Source File: login.module.ts    From office-hours with GNU General Public License v3.0 6 votes vote down vote up
@Module({
  imports: [
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get('JWT_SECRET'),
      }),
    }),
  ],
  controllers: [LoginController],
  providers: [JwtStrategy, LoginCourseService],
})
export class LoginModule {}
Example #13
Source File: app.module.ts    From twilio-voice-notification-app with Apache License 2.0 6 votes vote down vote up
/**
 * Main module used in Development and Production.
 * It uses PostgreSQL database connector.
 */
@Module({
  imports: [
    TwilioModule,
    SharedModule.forRoot(shouldServeStaticContent),
    SequelizeModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        const database = configService.get<any>(ENV_VAR.DATABASE_KEY);
        return {
          dialect: 'postgres',
          ...database,
          synchronize: true,
          dialectOptions: {
            ssl: {
              rejectUnauthorized: false
            }
          },
          ssl: true,
          models: [TestCall, Call, Broadcast],
        };
      },
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {
  constructor(sequelize: Sequelize) {
    // It will create the database the first time.
    // For a list of options, see: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-sync
    sequelize.sync();
  }
}
Example #14
Source File: main.ts    From nestjs-starter with MIT License 6 votes vote down vote up
async function bootstrap(): Promise<void> {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: WinstonModule.createLogger(loggerConfig),
  });
  const logger = app.get(WINSTON_MODULE_NEST_PROVIDER);
  const configService = app.get(ConfigService);

  app.enableCors({
    credentials: true,
    origin: configService.get('CLIENT_URL'),
  });
  app.enableShutdownHooks();
  app.get(AppModule).subscribeToShutdown(() => app.close());

  app.use(cookieParser(configService.get('COOKIE_SECRET')));
  app.use(loggerMiddleware);
  app.useGlobalFilters(new HttpExceptionFilter());
  app.useGlobalPipes(
    new CustomValidationPipe({
      forbidNonWhitelisted: true,
      forbidUnknownValues: true,
      whitelist: true,
    }),
  );
  setupApiDocs(app);

  await app.listen(configService.get('PORT')).then(() => {
    logger.log(`Server is running on port ${configService.get('PORT')}`);
  });
}
Example #15
Source File: app.module.ts    From 42_checkIn with GNU General Public License v3.0 5 votes vote down vote up
@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
      isGlobal: true,
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('database.host'),
        port: configService.get('database.port'),
        username: configService.get('database.username'),
        password: configService.get('database.password'),
        database: configService.get('database.name'),
        entities: [join(__dirname, '/**/*.entity.js')],
        synchronize: true,
      }),
    }),
    // ServeStaticModule.forRoot({
    //   rootPath: resolve(__dirname, '../../../client/build'),
    // }),
    TerminusModule,
    UserModule,
    AuthModule,
    CardModule,
    LogModule,
    HealthModule,
    LoggerModule,
    ThrottlerModule.forRoot({
      ttl: 60,
      limit: 20,
    }),
    WaitingModule,
    HttpModule,
    // MailerModule.forRootAsync({
    //   imports: [ConfigModule],
    //   inject: [ConfigService],
    //   useFactory: (configService: ConfigService) => ({
    //     transport: configService.get('mailer.mail'),
    //     defaults: {
    //       from: '"42 출입 시스템" <[email protected]>',
    //     },
    //     template: {
    //       dir: __dirname + '/templates',
    //       adapter: new EjsAdapter(),
    //       options: {
    //         strict: true,
    //       },
    //     },
    //   }),
    // }),
    ScheduleModule.forRoot(),
  ],
  controllers: [AppController, HealthController, WaitingController],
  providers: [
    AppService,
    Logger,
    { provide: APP_GUARD, useClass: TokenThrottlerGuard },
  ],
})
export class AppModule {}
Example #16
Source File: auth.controller.ts    From nest-js-boilerplate with MIT License 5 votes vote down vote up
constructor(
    private readonly authService: AuthService,
    private readonly jwtService: JwtService,
    private readonly usersService: UsersService,
    private readonly configService: ConfigService,
  ) { }