Skip to content

Instantly share code, notes, and snippets.

@Nathan-Bernardo
Created November 15, 2023 18:24
Show Gist options
  • Save Nathan-Bernardo/bcb98b2215571223299209b9088489f2 to your computer and use it in GitHub Desktop.
Save Nathan-Bernardo/bcb98b2215571223299209b9088489f2 to your computer and use it in GitHub Desktop.
LOADER=fileLoader
PORT=9000
app:
somePort: ${PORT:-12345}
envLoader: fileLoader
port: 5005
apiPrefix: api-blob
environment: development
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypedConfigModule, fileLoader } from 'nest-typed-config';
import { AppConfig } from '#config/configuration';
@Module({
imports: [
TypedConfigModule.forRoot({
schema: AppConfig,
load: fileLoader({ ignoreEnvironmentVariableSubstitution: false }),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
import { Transform, Type } from 'class-transformer';
import {
IsArray,
IsDefined,
IsInt,
IsNumber,
IsOptional,
IsString,
ValidateNested,
} from 'class-validator';
export class GeneralConfig {
@IsNumber()
@Type(() => Number)
public readonly somePort!: number;
@IsInt()
@IsOptional()
public readonly port: number = 5005;
@IsString()
@IsOptional()
public readonly envLoader: string;
@IsString()
@IsOptional()
public readonly apiPrefix: string = 'api-blob';
@IsString()
@IsOptional()
public readonly environment: string = 'development';
}
export class AppConfig {
@Type(() => GeneralConfig)
@ValidateNested()
@IsDefined()
public readonly app: GeneralConfig;
}
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { json, urlencoded } from 'body-parser';
import * as cookieParser from 'cookie-parser';
import { Logger, ValidationPipe } from '@nestjs/common';
import { AppConfig } from '#config/configuration';
async function bootstrap() {
const environment = process.env.NODE_ENV || 'development';
const app = await NestFactory.create(AppModule, {
logger:
environment === 'development'
? ['debug', 'log', 'warn', 'error']
: ['log', 'warn', 'error'],
});
// validation pipe
app.useGlobalPipes(new ValidationPipe());
// body-parser
app.use(urlencoded({ extended: true }));
app.use(json({ limit: '1000mb' }));
// cookie-parser
app.use(cookieParser());
// cors
app.enableCors({ origin: true, credentials: true });
// Pre setup
const logger = new Logger();
const configService = app.get(AppConfig);
const apiPrefix = configService.app.apiPrefix;
app.setGlobalPrefix(apiPrefix);
const port = configService.app.port;
console.log('SOME PORT');
console.log(configService.app.somePort);
await app.listen(port, () => {
logger.log(`DTF Cron API is running at port ${port}`);
logger.log(`API prefix: ${apiPrefix}`);
});
}
bootstrap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment