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

add solution for 4-module 1-task #5

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
Empty file.
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
import {ArgumentsHost, Catch, ExceptionFilter, HttpException} from "@nestjs/common";
import { Response } from 'express';
import fs from 'node:fs';

@Catch(HttpException)
export class HttpErrorFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {}
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const dateString = new Date().toISOString();
const logMessage = `[${dateString}] ${status} - ${exception.message}\n`;
fs.appendFileSync('errors.log', logMessage);

response.status(status).json({
statusCode: status,
message: exception.message,
timestamp: dateString,
});
}
}
13 changes: 11 additions & 2 deletions 04-request-lifecycle/01-nestjs-components/guards/roles.guard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { CanActivate, ExecutionContext } from "@nestjs/common";
import {CanActivate, ExecutionContext, ForbiddenException, Injectable} from "@nestjs/common";

@Injectable()
export class RolesGuard implements CanActivate {
canActivate(context: ExecutionContext) {}
canActivate(context: ExecutionContext) {
const request = context.switchToHttp().getRequest();
const userRole = request.headers["x-role"];
if(userRole !== "admin") {
throw new ForbiddenException('Доступ запрещён: требуется роль admin')
}

return true;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import {NestInterceptor, ExecutionContext, CallHandler, Injectable} from "@nestjs/common";
import { map } from "rxjs/operators";

@Injectable()
export class ApiVersionInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {}
intercept(context: ExecutionContext, next: CallHandler) {
const startTime = new Date().getTime();
return next.handle().pipe(
map((data) => ({
...data,
apiVersion: "1.0",
executionTime: (new Date().getTime()) - startTime + 'ms'
})),
);
}
}
2 changes: 2 additions & 0 deletions 04-request-lifecycle/01-nestjs-components/main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import {HttpErrorFilter} from "./filters/http-error.filter";

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpErrorFilter());
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { NestMiddleware } from "@nestjs/common";
import {Injectable, NestMiddleware} from "@nestjs/common";
import { Request, Response, NextFunction } from "express";

@Injectable()
export class LoggingMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {}
use(req: Request, res: Response, next: NextFunction) {
console.log(`[${req.method}] ${req.url}`);
next(); // Передаём управление следующему обработчику
}
}
12 changes: 10 additions & 2 deletions 04-request-lifecycle/01-nestjs-components/pipes/parse-int.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { PipeTransform } from "@nestjs/common";
import {BadRequestException, Injectable, PipeTransform} from "@nestjs/common";

@Injectable()
export class ParseIntPipe implements PipeTransform {
transform(value: string): number {}
transform(value: string): number {
const result = +value;
if(isNaN(result)){
throw new BadRequestException(`"${value}" не является числом`);
}

return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,40 @@ import {
Delete,
Get,
Param,
ParseIntPipe,
Patch,
Post,
Post, UseGuards, UseInterceptors,
} from "@nestjs/common";
import { TasksService } from "./tasks.service";
import { CreateTaskDto, UpdateTaskDto } from "./task.model";
import {ParseIntPipe} from "../pipes/parse-int.pipe";
import {RolesGuard} from "../guards/roles.guard";
import {ApiVersionInterceptor} from "../interceptors/api-version.interceptor";

@Controller("tasks")
export class TasksController {
constructor(private readonly tasksService: TasksService) {}

@Get()
getAllTasks() {
@UseInterceptors(ApiVersionInterceptor)
async getAllTasks() {
return this.tasksService.getAllTasks();
}

@Get(":id")
getTaskById(@Param("id", ParseIntPipe) id: number) {
@UseInterceptors(ApiVersionInterceptor)
getTaskById(@Param("id", new ParseIntPipe()) id: number) {
return this.tasksService.getTaskById(id);
}

@Post()
@UseGuards(RolesGuard)
@UseInterceptors(ApiVersionInterceptor)
createTask(@Body() task: CreateTaskDto) {
return this.tasksService.createTask(task);
}

@Patch(":id")
@UseInterceptors(ApiVersionInterceptor)
updateTask(
@Param("id", ParseIntPipe) id: number,
@Body() task: UpdateTaskDto,
Expand All @@ -39,6 +46,8 @@ export class TasksController {
}

@Delete(":id")
@UseGuards(RolesGuard)
@UseInterceptors(ApiVersionInterceptor)
deleteTask(@Param("id", ParseIntPipe) id: number) {
return this.tasksService.deleteTask(id);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { Module } from "@nestjs/common";
import {MiddlewareConsumer, Module, NestModule} from "@nestjs/common";
import { TasksController } from "./tasks.controller";
import { TasksService } from "./tasks.service";
import {LoggingMiddleware} from "../middlewares/logging.middleware";

@Module({
imports: [],
controllers: [TasksController],
providers: [TasksService],
})
export class TasksModule {}
export class TasksModule implements NestModule{
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes("/");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { CreateTaskDto, Task, TaskStatus, UpdateTaskDto } from "./task.model";
export class TasksService {
private tasks: Task[] = [];

getAllTasks() {
async getAllTasks() {
return { tasks: this.tasks };
}

Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"sqlite3": "^5.1.7",
"typeorm": "^0.3.20"
"typeorm": "^0.3.20",
"@types/lodash": "^4.17.13",
"lodash": "^4.17.21"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
Expand Down
Loading