-
Notifications
You must be signed in to change notification settings - Fork 1
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
34 changes: 18 additions & 16 deletions
34
02-nestjs-basics/01-tasks-controller/tasks/tasks.controller.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
106
02-nestjs-basics/01-tasks-controller/tasks/tasks.service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
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; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
супер! 👍