Skip to content

Instantly share code, notes, and snippets.

@albizan
Last active April 3, 2019 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save albizan/ac47647a0b48c945251f1dbedd6b7c66 to your computer and use it in GitHub Desktop.
Save albizan/ac47647a0b48c945251f1dbedd6b7c66 to your computer and use it in GitHub Desktop.
How to Inject configService in main.ts ?
import { Module } from '@nestjs/common';
import { ConfigService } from './config.service';
@Module({
providers: [
{
provide: ConfigService,
useValue: new ConfigService(`${process.env.NODE_ENV}.env`),
},
],
exports: [ConfigService],
})
export class ConfigModule {}
import * as dotenv from 'dotenv';
import * as fs from 'fs';
export class ConfigService {
private readonly envConfig: { [key: string]: string };
constructor(filePath: string) {
this.envConfig = dotenv.parse(fs.readFileSync(filePath));
}
get(key: string): string {
return this.envConfig[key];
}
getDbType() {
return ('postgres' as 'postgres');
}
}
// Load ENV_VARIABLES
import * as dotenv from 'dotenv';
dotenv.config();
import { NestFactory } from '@nestjs/core';
import { Logger, ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
import {ConfigService} from './config/config.service';
import * as helmet from 'helmet';
async function bootstrap() {
const config: ConfigService = new ConfigService(`${process.env.NODE_ENV}.env`);
const app = await NestFactory.create(AppModule);
const HTTP_PORT = config.get('HTTP_PORT');
// Use Middleware
app.enableCors();
app.use(helmet());
/* Use Validation on all endpoints with a global validation Pipe */
app.useGlobalPipes(new ValidationPipe());
await app.listen(HTTP_PORT);
Logger.log(`App running on port ${HTTP_PORT}`, 'Application Bootstrap');
}
bootstrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment