From a00c5b0650f320cc9d0fed08cf0f963448a3e94a Mon Sep 17 00:00:00 2001 From: Sambo Chea Date: Tue, 14 Sep 2021 10:51:24 +0700 Subject: [PATCH] Task: Updated the delete route and controller --- README.md | 10 +++++++++- src/controller/person.controller.ts | 29 ++++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2de971e..059f412 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ curl http://localhost:3000/info ```typescript import { Request, Response } from "express" import Controller from "../decorators/controller.decorator" -import { Get, Post } from "../decorators/handlers.decorator" +import { Get, Post, Delete } from "../decorators/handlers.decorator" const data: any[] = [] @@ -70,6 +70,14 @@ export default class HomeController { body: body, }) } + + @Delete("/:id") + public get(req: Request, res: Response) { + const id = req.params.id + res.json({ + id: id, + }) + } } ``` diff --git a/src/controller/person.controller.ts b/src/controller/person.controller.ts index 0879876..e83ac18 100644 --- a/src/controller/person.controller.ts +++ b/src/controller/person.controller.ts @@ -1,6 +1,6 @@ import { Request, Response } from "express" import Controller from "../decorators/controller.decorator" -import { Post, Get } from "../decorators/handlers.decorator" +import { Post, Get, Delete } from "../decorators/handlers.decorator" const persons: Array = [ { @@ -33,4 +33,31 @@ export default class PersonController { body: person, }) } + + @Delete("/:id") + public deletePerson(req: Request, res: Response) { + const id = req.params.id + + if (id == null) { + return res.status(400).json({ + status: 400, + message: "Id is required", + }) + } + + const person = persons.find((person) => person.id === Number(id)) + + if (person == null) { + return res.status(404).json({ + status: 404, + message: "Person not found", + }) + } + + persons.splice(persons.indexOf(person), 1) + res.json({ + message: "Person deleted successfully", + body: person, + }) + } }