Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pdt24 25 | Create a wrapper for environment variables #9

Merged
merged 16 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# Application
APP_PORT=3000
APP_ENV=development
NODE_ENV=development # development || production

# Database
POSTGRES_USER=trainee
POSTGRES_PASSWORD=root9996
DB_HOST=postgres #should be localhost if db is running in docker and app is running in container
POSTGRES_PORT=5432
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_DB=url_shortener
POSTGRES_PORT= 5432
DB_HOST= postgres


# JWT
JWT_SECRET=your_jwt_secret
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,5 @@ pids

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

ormconfig.json
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this file be ignored @pratham-outside

7 changes: 7 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ services:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
APP_PORT: ${APP_PORT}
NODE_ENV: ${NODE_ENV}
EMAIL_SERVICE: ${EMAIL_SERVICE}
EMAIL_HOST: ${EMAIL_HOST}
EMAIL_PORT: ${EMAIL_PORT}
EMAIL_USER: ${EMAIL_USER}
EMAIL_PASS: ${EMAIL_PASS}

ports:
- ${APP_PORT}:${APP_PORT}
networks:
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"dotenv": "^16.4.7",
"pg": "^8.13.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20"
"typeorm": "^0.3.20",
"zod": "^3.24.1"
},
"devDependencies": {
"@commitlint/cli": "^19.6.0",
Expand Down
2 changes: 1 addition & 1 deletion src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { AppService } from '@/app.service';

@Controller()
export class AppController {
Expand Down
11 changes: 6 additions & 5 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/db.module';
import { Module } from '@nestjs/common';
import { AppController } from '@/app.controller';
import { AppService } from '@/app.service';
import { validate } from '@/config/env.config';
import { DatabaseModule } from '@/database/db.module';

@Module({
imports: [ConfigModule.forRoot({ isGlobal: true }), DatabaseModule],
imports: [ConfigModule.forRoot({ isGlobal: true, validate }), DatabaseModule],
controllers: [AppController],
providers: [AppService],
})
Expand Down
50 changes: 50 additions & 0 deletions src/config/env.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { z } from 'zod';
export const env = {
POSTGRES_DB: process.env.POSTGRES_DB,
POSTGRES_USER: process.env.POSTGRES_USER,
POSTGRES_PASSWORD: process.env.POSTGRES_PASSWORD,
POSTGRES_PORT: +(process.env.POSTGRES_PORT || 5432),
DB_HOST: process.env.DB_HOST,
APP_PORT: +(process.env.APP_PORT || 3000),
noxiousghost marked this conversation as resolved.
Show resolved Hide resolved
NODE_ENV: process.env.NODE_ENV,
EMAIL_HOST: process.env.EMAIL_HOST,
EMAIL_PASS: process.env.EMAIL_PASS,
EMAIL_USER: process.env.EMAIL_USER,
EMAIL_PORT: +(process.env.EMAIL_PORT || 587),
} as const;

export enum APP_ENVIRONVENT {
DEVELOPMENT = 'development',
PRODUCTION = 'production',
}

enum SMTP_PORTS {
STANDARD = 25,
DEFAULT = 587,
TLS = 465,
}
const validationSchema = z
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validationSchema-> appEnvSchema

.object({
POSTGRES_DB: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
POSTGRES_USER: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
POSTGRES_PASSWORD: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
POSTGRES_PORT: z.number().gt(0, { message: 'Port cannot be empty' }),
DB_HOST: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
APP_PORT: z.number().gt(0, { message: 'Port cannot be empty' }),
NODE_ENV: z.nativeEnum(APP_ENVIRONVENT),
EMAIL_HOST: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
EMAIL_PORT: z.nativeEnum(SMTP_PORTS),
EMAIL_USER: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
EMAIL_PASS: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
})
.required();

type ValidationSchema = z.infer<typeof validationSchema>;

export const validate = (): ValidationSchema => {
const value = validationSchema.safeParse(env);
if (!value.success) {
throw new Error(`---${value.error.issues[0].path} :: ${value.error.issues[0].message.toUpperCase()}---`);
noxiousghost marked this conversation as resolved.
Show resolved Hide resolved
}
return value.data;
};
5 changes: 3 additions & 2 deletions src/database/db.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { dataBaseConfigurations } from 'src/scripts/orm.config';
import { dataBaseConfigurations } from '@/scripts/orm.config';
import { DataSource, DataSourceOptions, TypeORMError } from 'typeorm';
import { env } from '@/config/env.config';

@Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: () => {
return {
host: process.env.DB_HOST,
host: env.DB_HOST,
...dataBaseConfigurations,
} as TypeOrmModuleOptions;
},
Expand Down
10 changes: 5 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AppModule } from '@/app.module';
import { env } from '@/config/env.config';

async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);

await app.listen(process.env.APP_PORT ?? 3000, () => {
console.info('Listening to server....');
console.info(`Server listening at port http://localhost:${process.env.APP_PORT}`);
const port = env.APP_PORT;
await app.listen(port, () => {
console.info(`${env.NODE_ENV?.toLocaleUpperCase()} Server listening at port ${port}`);
});
}

Expand Down
11 changes: 6 additions & 5 deletions src/scripts/orm.config.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { DataSource, DataSourceOptions } from 'typeorm';
import { env, APP_ENVIRONVENT } from '@/config/env.config';

const dataBaseConfigurations = {
type: 'postgres',
port: +(process.env.POSTGRES_PORT ?? '5432'),
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
synchronize: false, // Should be false in production to use migrations
port: +env.POSTGRES_PORT,
username: env.POSTGRES_USER,
password: env.POSTGRES_PASSWORD,
database: env.POSTGRES_DB,
synchronize: env.NODE_ENV === APP_ENVIRONVENT.DEVELOPMENT, // Should be false in production to use migrations
logging: true,
entities: [join(__dirname, '/../entities', '*.entity.{ts,js}')],
migrations: [join(__dirname, '/../migrations', '*.{ts,js}')],
Expand Down
7 changes: 6 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1623,7 +1623,7 @@ [email protected]:
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.4.5.tgz#cdd3b3b604cb327e286b4762e13502f717cb099f"
integrity sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==

dotenv@^16.0.3:
dotenv@^16.0.3, dotenv@^16.4.7:
version "16.4.7"
resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-16.4.7.tgz#0e20c5b82950140aa99be360a8a5f52335f53c26"
integrity sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==
Expand Down Expand Up @@ -4375,3 +4375,8 @@ yocto-queue@^1.0.0:
version "1.1.1"
resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-1.1.1.tgz#fef65ce3ac9f8a32ceac5a634f74e17e5b232110"
integrity sha512-b4JR1PFR10y1mKjhHY9LaGo6tmrgjit7hxVIeAmyMw3jegXR4dhYqLaQF5zMXZxY7tLpMyJeLjr1C4rLmkVe8g==

zod@^3.24.1:
version "3.24.1"
resolved "https://registry.yarnpkg.com/zod/-/zod-3.24.1.tgz#27445c912738c8ad1e9de1bea0359fa44d9d35ee"
integrity sha512-muH7gBL9sI1nciMZV67X5fTKKBLtwpZ5VBp1vsOQzj1MhrBZ4wlVCm3gedKZWLp0Oyel8sIGfeiz54Su+OVT+A==
Loading