Skip to content

Commit

Permalink
add solution for 2-module 2-task
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Demidkin committed Dec 12, 2024
1 parent f142f13 commit e8c43cb
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 7 deletions.
4 changes: 4 additions & 0 deletions 02-nestjs-basics/02-filtering/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,9 @@
"scripts": {
"start": "nest start --watch",
"test": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --no-warnings --experimental-vm-modules\" NODE_ENV=test jest --config jest.config.js --runInBand"
},
"dependencies": {
"@types/lodash": "^4.17.13",
"lodash": "^4.17.21"
}
}
4 changes: 4 additions & 0 deletions 02-nestjs-basics/02-filtering/tasks/task.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ export interface Task {
description: string;
status: TaskStatus;
}

export type TaskKeys = keyof Task

export const TASK_KEYS:TaskKeys[] = ['id', 'status', 'description', 'status'];
30 changes: 27 additions & 3 deletions 02-nestjs-basics/02-filtering/tasks/tasks.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Controller, Get, Query } from "@nestjs/common";
import {Controller, Get, HttpException, HttpStatus, Query} from "@nestjs/common";
import { TasksService } from "./tasks.service";
import { TaskStatus } from "./task.model";
import {TASK_KEYS, TaskKeys, TaskStatus} from "./task.model";

@Controller("tasks")
export class TasksController {
Expand All @@ -11,5 +11,29 @@ export class TasksController {
@Query("status") status?: TaskStatus,
@Query("page") page?: number,
@Query("limit") limit?: number,
) {}
@Query("sortBy") sortBy?: TaskKeys,
) {
const wrongSortParameter = sortBy && !TASK_KEYS.includes(sortBy);
const wrongPageParameter = page && typeof Number(page) !== "number"
|| page && page < 1
const wrongLimitParameter = limit && typeof Number(limit) !== "number"
|| limit && limit < 1
const wrongStatusParameter = status && !Object.values(TaskStatus).includes(status);

if(wrongLimitParameter) {
throw new HttpException(`Wrong limit parameter`, HttpStatus.BAD_REQUEST);
}
if(wrongPageParameter ) {
throw new HttpException(`Wrong page parameter`, HttpStatus.BAD_REQUEST);
}
if(wrongSortParameter) {
throw new HttpException(`Wrong sortBy parameter`, HttpStatus.BAD_REQUEST);
}

if(wrongStatusParameter) {
throw new HttpException(`Wrong task status:${status}`, HttpStatus.NOT_FOUND);
}

return this.tasksService.getFilteredTasks(status, page, limit, sortBy);
}
}
58 changes: 55 additions & 3 deletions 02-nestjs-basics/02-filtering/tasks/tasks.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import { Injectable } from "@nestjs/common";
import { Task, TaskStatus } from "./task.model";
import {Injectable} from "@nestjs/common";
import {Task, TaskKeys, TaskStatus} from "./task.model";
import {chunk} from "lodash";

//метод сортировки задач по полям
const sortByTaskField = (sortBy: TaskKeys, tasks:Task[]) => tasks.sort((taskA, taskB)=> {
//если поле сортировки "id" то сравниваем как числа
let valueA: number | string = sortBy === 'id' ? Number(taskA[sortBy]) : taskA[sortBy];
let valueB: number | string = sortBy === 'id' ? Number(taskB[sortBy]) : taskB[sortBy];

if(valueA < valueB) {
return -1;
}

if(valueA > valueB) {
return 1;
}

return 0;
})

@Injectable()
export class TasksService {
Expand Down Expand Up @@ -40,5 +58,39 @@ export class TasksService {
status?: TaskStatus,
page?: number,
limit?: number,
): Task[] {}
sortBy?: TaskKeys,
): Task[] {
let result = this.tasks;
//сначала фильтруем задачи по статусу
if(status) {
result = result.filter(task => task.status === status);
}

//сортируем по полю, если нужно
if(sortBy) {
result = sortByTaskField(sortBy, result);
}

//если есть limit
if(limit) {
//разбиваем одномерный массив задач.
//получаем двумерный. Кол-во элементов во вложенном = limit
const tasksByPage = chunk(result, limit);

//если есть page и он больше 1,
// то обращаемся к массиву задач по индексу page - 1.
//если элемента с таким индексом нет, то возвращаем пустой массив
//если же page нет, то возвращаем первый элемент
return (page)
? tasksByPage[page - 1] ?? []
: tasksByPage[0]
}

//если нет лимита и page больше 1,то возвращаем пустой массив
if(page && page > 1) {
return []
}

return result
}
}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,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

0 comments on commit e8c43cb

Please sign in to comment.