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 7 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
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
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ services:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
APP_PORT: ${APP_PORT}
NODE_ENV: ${NODE_ENV}
ports:
- ${APP_PORT}:${APP_PORT}
networks:
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
"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
3 changes: 2 additions & 1 deletion 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 { validate } from './config/env.config';
import { ConfigModule } from '@nestjs/config';
Copy link
Collaborator

Choose a reason for hiding this comment

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

Please prefer import aliases "@/*" rather than relative imports.

It will help a lot for code organization.

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
48 changes: 48 additions & 0 deletions src/config/env.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { z } from 'zod';
export const envVariables = {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
export const envVariables = {
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;

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();

export const validate = (): object => {
Copy link
Collaborator

@rrojan rrojan Dec 27, 2024

Choose a reason for hiding this comment

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

Use return type z.infer<typeof validationSchema> instead of object

const value = validationSchema.safeParse(envVariables);
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;
};
3 changes: 2 additions & 1 deletion src/database/db.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { dataBaseConfigurations } from 'src/scripts/orm.config';
import { DataSource, DataSourceOptions, TypeORMError } from 'typeorm';
import { envVariables } from '@/config/env.config';

@Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: () => {
return {
host: process.env.DB_HOST,
host: envVariables.DB_HOST,
...dataBaseConfigurations,
} as TypeOrmModuleOptions;
},
Expand Down
8 changes: 4 additions & 4 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 { envVariables } 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 = envVariables.APP_PORT;
await app.listen(port, () => {
console.info(`Server listening at port ${port}`);
});
}

Expand Down
9 changes: 5 additions & 4 deletions src/scripts/orm.config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { DataSource, DataSourceOptions } from 'typeorm';
import { envVariables } 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,
port: +(envVariables.POSTGRES_PORT ?? '5432'),
Copy link
Collaborator

Choose a reason for hiding this comment

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

After we return z.infer<typeof validationSchema> env.POSTGRES_PORT will not be falsey.

username: envVariables.POSTGRES_USER,
password: envVariables.POSTGRES_PASSWORD,
database: envVariables.POSTGRES_DB,
synchronize: false, // Should be false in production to use migrations
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
database: envVariables.POSTGRES_DB,
synchronize: false, // Should be false in production to use migrations
database: envVariables.POSTGRES_DB,
synchronize: ${env.NODE_ENV === APP_ENVIRONVENT.PRODUCTION}

Copy link
Collaborator

Choose a reason for hiding this comment

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

Typo:
env.NODE_ENV !== APP_ENVIRONVENT.PRODUCTION

logging: true,
entities: [join(__dirname, '/../entities', '*.entity.{ts,js}')],
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
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