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 2-module 1-task #2

Merged
merged 1 commit into from
Dec 11, 2024
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
34 changes: 18 additions & 16 deletions 02-nestjs-basics/01-tasks-controller/tasks/tasks.controller.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
} from "@nestjs/common";
import { TasksService } from "./tasks.service";
import { Task } from "./task.model";
import {Body, Controller, Delete, Get, Param, Patch, Post,} from "@nestjs/common";
import {TasksService} from "./tasks.service";
import {Task} from "./task.model";

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

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

@Get(":id")
getTaskById(@Param("id") id: string) {}
getTaskById(@Param("id") id: string) {
return this.tasksService.getTaskById(id);
}

@Post()
createTask(@Body() task: Task) {}
createTask(@Body() task: Task) {
return this.tasksService.createTask(task);
}

@Patch(":id")
updateTask(@Param("id") id: string, @Body() task: Task) {}
updateTask(@Param("id") id: string, @Body() task: Task) {
return this.tasksService.updateTask(id, task);
}

@Delete(":id")
deleteTask(@Param("id") id: string) {}
deleteTask(@Param("id") id: string) {
return this.tasksService.deleteTask(id);
}
}
106 changes: 99 additions & 7 deletions 02-nestjs-basics/01-tasks-controller/tasks/tasks.service.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,109 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { Task } from "./task.model";
import {HttpException, HttpStatus, Injectable} from "@nestjs/common";
import {Task} from "./task.model";

//сортировка id:string как number по порядку
const sortIdsAsNumbers = (idA:string, idB:string) => (Number(idA) - Number(idB));
//сортировка задач по id
Copy link

Choose a reason for hiding this comment

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

супер! 👍

const sortTasksById = (taskA:Task, taskB:Task) => sortIdsAsNumbers(taskA.id, taskB.id);
//получаем сортированный массив id задач
const getSortedTaskIds = (tasks: Task[]) => tasks
.map(task => task.id)
.sort(sortIdsAsNumbers)


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

getAllTasks(): Task[] {}
getAllTasks(): Task[] {
return this.tasks;
}

getTaskById(id: string): Task | null {
const targetTask = this.tasks.find(task => task.id === id);
if(!targetTask) {
throw new HttpException(`no task with id:${id}`, HttpStatus.NOT_FOUND);
}

return targetTask;
}

createTask(task: Task): Task {
let {id} = task;

//получаем массив id существующих задач и сортируем его
const taskIds = getSortedTaskIds(this.tasks);

//если входной параметр id уже есть в списке существующих,то ошибка
if(taskIds.includes(id)) {
throw new HttpException(`Task with id ${id} already exist`, HttpStatus.I_AM_A_TEAPOT);
}

//если id указан, то используем его
//если нет, то создаем id увеличением макс id на 1
const newTaskId = Boolean(id)
? id
: taskIds.length > 0
? `${Number(taskIds[taskIds.length - 1]) + 1}`
: '0'

//устанавливаем найденный id для новой задачи
const newTask: Task = {
...task,
id: newTaskId
}

//добавляем новую задачу в массив задач
//сортируем массив по id
this.tasks = [
...this.tasks,
newTask
].sort(sortTasksById);

return newTask;
}

updateTask(id: string, update: Task): Task {
let {id:updateTaskId} = update;
//ищем задачу для изменения по id
const targetTask = this.tasks.find(task => task.id === id);
//если задачи с таким id нет, то и обновлять нечего
if(!targetTask) {
throw new HttpException(`Can't find task with id:${id}`, HttpStatus.NOT_FOUND);
}
//если внутри объекта task.id есть и он не равен аргументу id,
//то нужно проверить, что в массиве задач нет задачи с таким id
if(
updateTaskId
&& updateTaskId !== id
&& this.tasks.some(task => task.id === updateTaskId)
) {
throw new HttpException(`Wrong task id:${updateTaskId}. Item with this id already exits`, HttpStatus.I_AM_A_TEAPOT);
}

//фильтруем все задачи, убирая редактируемую
const otherTasks = this.tasks.filter(task => task.id !== id);
const updatedTask = {
...targetTask,
...update,
}

this.tasks = [
...otherTasks,
updatedTask
].sort(sortTasksById);

getTaskById(id: string): Task {}

createTask(task: Task): Task {}
return updatedTask
}

updateTask(id: string, update: Task): Task {}
deleteTask(id: string): Task {
const targetTask = this.tasks.find(task => task.id === id);
if(!targetTask) {
throw new HttpException(`Can't find task with id:${id}`, HttpStatus.NOT_FOUND);
}
this.tasks = this.tasks.filter(task => task.id !== id);

deleteTask(id: string): Task {}
return targetTask;
}
}
Loading