Skip to content

Commit

Permalink
PDT24-24 | Create logger wrapper (#10)
Browse files Browse the repository at this point in the history
* feat: add logging service with winston

* chore(logging): use and fix logging information

* PDT24-34 | Configure nodemailer service (#12)

* feat: configure nodemailer servie for sending email

* feat: create a basic email template for sending signup otp code

* chore: rename param names and add function documentation

* fix: use secure mailing port

* refactor: remove sendEmail call from main and improve sendEmail method

* refactor: remove ternary operator
  • Loading branch information
noxiousghost authored Dec 31, 2024
1 parent 030b1ba commit 0947ed2
Show file tree
Hide file tree
Showing 10 changed files with 909 additions and 645 deletions.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@
"bcrypt": "^5.1.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"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"
"typeorm": "^0.3.20",
"winston": "^3.17.0"
},
"devDependencies": {
"@commitlint/cli": "^19.6.0",
Expand All @@ -49,6 +52,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
16 changes: 16 additions & 0 deletions src/config/logger.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { format, transports } from 'winston';
const isProduction = process.env.APP_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' }),
new transports.File({ filename: 'logs/all.log' }),
]
: [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 @@ -2,6 +2,9 @@ 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 { Logger } from '@nestjs/common';

const logger = new Logger();

@Module({
imports: [
Expand All @@ -15,7 +18,7 @@ import { DataSource, DataSourceOptions, TypeORMError } from 'typeorm';
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
8 changes: 8 additions & 0 deletions src/mailer/dto/mailer.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Address } from 'nodemailer/lib/mailer';
export class MailerDto {
sender?: Address;
recipients: 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.service';

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

export class MailerService {
private readonly logger = new Logger();
transporter: Transporter = createTransport({
host: process.env.EMAIL_HOST,
port: 465,
secure: true,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});

async sendEmail(data: MailerDto): Promise<void> {
try {
const { sender, recipients, subject, html, text } = data;
const mailOptions: SendMailOptions = {
from: sender ?? {
name: process.env.EMAIL_SENDER_NAME as string,
address: process.env.EMAIL_USER as string,
},
to: recipients,
subject,
html,
text,
};
await this.transporter.sendMail(mailOptions);
this.logger.log('Mail sent successfully');
} catch (error) {
this.logger.error(`Error sending email:`, { error });
}
}
}
16 changes: 11 additions & 5 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
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';

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 logger = new Logger();
const port = process.env.APP_PORT ?? 3000;
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, () => {
logger.log(`App is listening on port ${port}`);
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/scripts/orm.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const dataBaseConfigurations = {
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
synchronize: false, // Should be false in production to use migrations
logging: true,
logging: process.env.APP_ENV !== 'production',
entities: [join(__dirname, '/../entities', '*.entity.{ts,js}')],
migrations: [join(__dirname, '/../migrations', '*.{ts,js}')],
};
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

0 comments on commit 0947ed2

Please sign in to comment.