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-45 | Fix Docker Hot-Reloading #11

Merged
merged 8 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# custom

# compiled output
/dist
/node_modules
Expand Down
5 changes: 4 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ services:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
ports:
- 5432:5432
- 5433:5432
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U trainee -d url_shortener']
interval: 6s
Expand Down Expand Up @@ -41,6 +41,9 @@ services:
- ${APP_PORT}:${APP_PORT}
networks:
- app-network
volumes:
- .:/usr/local/app
- /usr/local/app/node_modules

volumes:
database_volume:
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,14 @@
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"dotenv": "^16.4.7",
"nest-winston": "^1.9.7",
"nodemailer": "^6.9.16",
"pg": "^8.13.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20",
"zod": "^3.24.1"
"zod": "^3.24.1",
"winston": "^3.17.0"
},
"devDependencies": {
"@commitlint/cli": "^19.6.0",
Expand All @@ -51,6 +54,7 @@
"@types/bcrypt": "^5.0.2",
"@types/express": "^5.0.0",
"@types/node": "^20.3.1",
"@types/nodemailer": "^6.4.17",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"eslint": "^8.0.0",
Expand Down
2 changes: 2 additions & 0 deletions src/config/env.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const env = {
EMAIL_HOST: process.env.EMAIL_HOST,
EMAIL_PASS: process.env.EMAIL_PASS,
EMAIL_USER: process.env.EMAIL_USER,
EMAIL_SENDER_NAME: process.env.EMAIL_SENDER_NAME,
EMAIL_PORT: +(process.env.EMAIL_PORT || 587),
} as const;

Expand All @@ -38,6 +39,7 @@ const envSchema = z
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' }),
EMAIL_SENDER_NAME: z.string().min(2, { message: 'Must be atleast 2 characters long' }),
})
.required();

Expand Down
18 changes: 18 additions & 0 deletions src/config/logger.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { format, transports } from 'winston';
import { env } from '@/config/env.config';

const isProduction = env.NODE_ENV === 'production';
export const loggerConfig = {
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
format.printf(({ level, message, timestamp }) => {
return `${timestamp} [${level}]: ${message}`;
}),
),
transports: isProduction
? [
new transports.File({ filename: 'logs/errors.log', level: 'error' }),
Copy link
Collaborator

Choose a reason for hiding this comment

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

If possible, store logs for different dates in different log files.

E.g. errors_2024-12-32.log

To stay clear of potential timezone issues, use server time or UTC.

Copy link
Collaborator Author

@noxiousghost noxiousghost Dec 31, 2024

Choose a reason for hiding this comment

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

For this we'd have to install an additional package called winston-daily-rotate-file. I tried to so but that package cause issues related to typescript. In future, I'll create a separate ticket for this and solve this. For now, lets keep it as it is

new transports.File({ filename: 'logs/all.log' }),
Comment on lines +14 to +15
Copy link
Collaborator

Choose a reason for hiding this comment

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

Use { flags: 'a' } to append to log file instead of overwriting it on each rebuild.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It turns out that the existing code (without flags: 'a') works just fine. It doesn't overwrite the log files on each rebuild. so I am leaving as it is

]
: [new transports.Console({ format: format.combine(format.colorize({ all: true })) })],
};
5 changes: 4 additions & 1 deletion src/database/db.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { dataBaseConfigurations } from '@/database/db.config';
import { DataSource, DataSourceOptions, TypeORMError } from 'typeorm';
import { env } from '@/config/env.config';
import { Logger } from '@nestjs/common';

const logger = new Logger();

@Module({
imports: [
Expand All @@ -16,7 +19,7 @@ import { env } from '@/config/env.config';
dataSourceFactory: async (options: DataSourceOptions) => {
try {
const dataSource = await new DataSource(options).initialize();
console.log(' ------ Connected to Database successfully -----');
logger.log(' ------ Connected to Database successfully -----');
return dataSource;
} catch (error) {
throw new TypeORMError(`Error Connection to database , "${error}"`);
Expand Down
7 changes: 7 additions & 0 deletions src/mailer/dto/mailer.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Address } from 'nodemailer/lib/mailer';
export class MailerDto {
to: Address[];
subject: string;
html: string;
text?: string;
}
8 changes: 8 additions & 0 deletions src/mailer/mailer.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { MailerService } from '@/mailer/mailer.service';

@Module({
providers: [MailerService],
exports: [MailerService],
})
export class MailerModule {}
38 changes: 38 additions & 0 deletions src/mailer/mailer.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { createTransport, SendMailOptions, Transporter } from 'nodemailer';
import { Logger } from '@nestjs/common';
import { MailerDto } from '@/mailer/dto/mailer.dto';
import { env } from '@/config/env.config';

export class MailerService {
private readonly logger = new Logger();
transporter: Transporter = createTransport({
host: env.EMAIL_HOST,
port: env.EMAIL_PORT,
secure: true,

auth: {
user: env.EMAIL_USER,
pass: env.EMAIL_PASS,
},
});

async sendEmail(data: MailerDto): Promise<void> {
try {
const { to, subject, html, text } = data;
const mailOptions: SendMailOptions = {
from: {
name: env.EMAIL_SENDER_NAME as string,
address: env.EMAIL_USER as string,
},
to,
subject,
html,
text,
};
await this.transporter.sendMail(mailOptions);
this.logger.log('Mail sent successfully');
} catch (error) {
this.logger.error(`Failed to send email: ${error}`);
}
}
}
11 changes: 9 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from '@/app.module';
import { WinstonModule } from 'nest-winston';
import { loggerConfig } from '@/config/logger.config';
import { Logger } from '@nestjs/common';
import { env } from '@/config/env.config';

async function bootstrap(): Promise<void> {
const app = await NestFactory.create(AppModule);
const logger = new Logger();
const port = env.APP_PORT;
const app = await NestFactory.create(AppModule, {
// this will overwrite the default logger of nestJS with custom winston logger
logger: WinstonModule.createLogger(loggerConfig),
});
await app.listen(port, () => {
console.info(`${env.NODE_ENV?.toLocaleUpperCase()} Server listening at port ${port}`);
logger.log(`App is listening on port ${port}`);
});
}

Expand Down
14 changes: 14 additions & 0 deletions src/template/email.template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const signupOtpMailTemplate = {
subject: 'Verify your account',
/**
* Generates a random OTP of the specified size.
* @param otpCode - code to send to through email.
* @param userName - name of the user to send the email to.
*/
body: (otpCode: number, userName: string): string => `
<div>
<p>Welcome ${userName}</p>
<p>Use this code to verify your account:<br><b>${otpCode}</b>
</div>
`,
};
Loading
Loading