Last active
April 3, 2019 14:45
-
-
Save albizan/ac47647a0b48c945251f1dbedd6b7c66 to your computer and use it in GitHub Desktop.
How to Inject configService in main.ts ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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