From b87d40ade891e08023a6ca722b4e6dc1891bebbd Mon Sep 17 00:00:00 2001 From: Peace Date: Thu, 5 Jun 2025 01:49:31 +0900 Subject: [PATCH] cat U D --- catDataMocking/src/cats/cats.route.ts | 71 +++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/catDataMocking/src/cats/cats.route.ts b/catDataMocking/src/cats/cats.route.ts index 3e70a59..054569f 100644 --- a/catDataMocking/src/cats/cats.route.ts +++ b/catDataMocking/src/cats/cats.route.ts @@ -50,4 +50,75 @@ router.get("/cats/:id", (req, res) => { } }); +// * U +router.put("/cats/:id", (req, res) => { + try { + const params = req.params; + const body = req.body; + let result; + const index = Cat.findIndex((cat) => cat.id === params.id); + if (index !== -1) { + const tempId = params.id; + const newCat = { ...body, id: tempId }; + Cat[index] = newCat; + result = newCat; + } + res.status(200).send({ + success: true, + data: { cat: result }, + }); + } catch (error) { + res.status(400).send({ + success: false, + error: error.message, + }); + } +}); + +router.patch("/cats/:id", (req, res) => { + try { + const params = req.params; + const body = req.body; + let result; + const index = Cat.findIndex((cat) => cat.id === params.id); + if (index !== -1) { + const tempId = params.id; + const newCat = { ...Cat[index], ...body, id: tempId }; + Cat[index] = newCat; + result = newCat; + } + res.status(200).send({ + success: true, + data: { cat: result }, + }); + } catch (error) { + res.status(400).send({ + success: false, + error: error.message, + }); + } +}); + +// * D +router.delete("/cats/:id", (req, res) => { + try { + const params = req.params; + const body = req.body; + let result; + const index = Cat.findIndex((cat) => cat.id === params.id); + if (index !== -1) { + Cat.splice(index, 1); + } + res.status(200).send({ + success: true, + data: { cat: result }, + }); + } catch (error) { + res.status(400).send({ + success: false, + error: error.message, + }); + } +}); + export default router;