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

Task 3: notification service realization #4

Closed
wants to merge 3 commits into from
Closed
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
9 changes: 9 additions & 0 deletions 03-di/01-notification-service/logger/logger.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface ILoggerService {
senderEmail(data: string): void;
smsGateway(data: string): void;
}

export enum LogPath {
emails = 'emails',
sms = 'sms',
}
8 changes: 8 additions & 0 deletions 03-di/01-notification-service/logger/logger.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from "@nestjs/common";
import { LoggerService } from "./Logger.service";

@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}
34 changes: 34 additions & 0 deletions 03-di/01-notification-service/logger/logger.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { Injectable } from "@nestjs/common";
import { appendFile } from "node:fs/promises";
import { ILoggerService, LogPath } from "./Logger.interface";

const emailsLogPath = require('path').join(__dirname, '..', '..', 'test', 'emails.txt');
const smsLogPath = require('path').join(__dirname, '..', '..', 'logs', 'sms.txt');
const errorsLogPath = require('path').join(__dirname, '..', '..', 'logs', 'errors.txt');
const newLineChar = process.platform === 'win32' ? '\r\n' : '\n';

@Injectable()
export class LoggerService implements ILoggerService {
public async senderEmail(data: string) {
await this._write(data, LogPath.emails);
}

public async smsGateway(data: string) {
await this._write(data, LogPath.sms);
}

private async _write(data: string, type: LogPath) {
try {
console.log(data);
const path = type === LogPath.emails ? emailsLogPath : smsLogPath;
await appendFile(path, this._preparedWriteFileData(data));
} catch (error: any) {
console.error(error);
await appendFile(errorsLogPath, this._preparedWriteFileData(error));
}
}

private _preparedWriteFileData(data: string) {
return new Uint8Array(Buffer.from(`${data}${newLineChar}`));
}
}
2 changes: 2 additions & 0 deletions 03-di/01-notification-service/logs/emails.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Email sent to [email protected]: [Новая задача] Вы назначены ответственным за задачу: "Сделать домашнюю работу"
Email sent to [email protected]: [Новая задача] Вы назначены ответственным за задачу: "Сделать домашнюю работу 1"
1 change: 1 addition & 0 deletions 03-di/01-notification-service/logs/errors.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Error: ENOENT: no such file or directory, open '/Users/nikolaylukinnych/Documents/nodejs-20241202_nikalun/03-di/01-notification-service/test/emails.txt'
2 changes: 2 additions & 0 deletions 03-di/01-notification-service/logs/sms.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SMS sent to +123456789: Статус задачи "New Task 1" обновлён на "completed"
SMS sent to +987654321: Статус задачи "Сделать домашнюю работу 1" обновлён на "completed"
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface INotificationsService {
sendEmail(to: string, subject: string, message: string): void;
sendSMS(to: string, message: string): void;
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Module } from "@nestjs/common";
import { NotificationsService } from "./notifications.service";
import { LoggerService } from "../logger/logger.service";

@Module({
providers: [NotificationsService],
imports: [],
exports: [NotificationsService],
providers: [NotificationsService, LoggerService],
})
export class NotificationsModule {}
Original file line number Diff line number Diff line change
@@ -1,4 +1,25 @@
import { Injectable } from "@nestjs/common";
import { Injectable, NotFoundException } from "@nestjs/common";
import { INotificationsService } from "./notifications.interface";
import { LoggerService } from "../logger/logger.service";

@Injectable()
export class NotificationsService {}
export class NotificationsService implements INotificationsService {
constructor(
private _loggerService: LoggerService,
) {}
public sendEmail(to: string, subject: string, message: string) {
const isThrowException = !to || !subject || !message;
if (isThrowException) throw new NotFoundException();
const email = `Email sent to ${to}: [${subject}] ${message}`;

this._loggerService.senderEmail(email).then();
}

public sendSMS(to: string, message: string) {
const isThrowException = !to || !message;
if (isThrowException) throw new NotFoundException();
const sms = `SMS sent to ${to}: ${message}`;

this._loggerService.smsGateway(sms).then();
}
}
5 changes: 4 additions & 1 deletion 03-di/01-notification-service/tasks/tasks.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Module } from "@nestjs/common";
import { TasksController } from "./tasks.controller";
import { TasksService } from "./tasks.service";
import { NotificationsService } from "../notifications/notifications.service";
import { UsersService } from "../users/users.service";
import { LoggerService } from "../logger/logger.service";

@Module({
imports: [],
controllers: [TasksController],
providers: [TasksService],
providers: [TasksService, NotificationsService, UsersService, LoggerService],
})
export class TasksModule {}
17 changes: 16 additions & 1 deletion 03-di/01-notification-service/tasks/tasks.service.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { CreateTaskDto, Task, TaskStatus, UpdateTaskDto } from "./task.model";
import { NotificationsService } from "../notifications/notifications.service";
import { UsersService } from "../users/users.service";

@Injectable()
export class TasksService {
private tasks: Task[] = [];

constructor() {}
constructor(
private _notificationService: NotificationsService,
private _userService: UsersService,
) {}

async createTask(createTaskDto: CreateTaskDto) {
const { title, description, assignedTo } = createTaskDto;
const { email } = this._userService.getUserById(assignedTo);

const task: Task = {
id: (this.tasks.length + 1).toString(),
title,
Expand All @@ -17,15 +24,23 @@ export class TasksService {
assignedTo,
};
this.tasks.push(task);
const message = `Вы назначены ответственным за задачу: "${title}"`;

this._notificationService.sendEmail(email, 'Новая задача', message);

return task;
}

async updateTask(id: string, updateTaskDto: UpdateTaskDto) {
const task = this.tasks.find((t) => t.id === id);
if (!task) {

throw new NotFoundException(`Задача с ID ${id} не найдена`);
}
const { phone } = this._userService.getUserById(task.assignedTo);
const message = `Статус задачи "${task.title}" обновлён на "${updateTaskDto.status}"`;

this._notificationService.sendSMS(phone, message);

Object.assign(task, updateTaskDto);
return task;
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^8.1.0",
"@nestjs/typeorm": "^10.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
Expand Down
Loading