From d2a132e812dd4d79892f3e9ee416b8e2645e1654 Mon Sep 17 00:00:00 2001
From: elit04 <elit04@fu-berlin.de>
Date: Mon, 24 Jan 2022 13:29:24 -0500
Subject: [PATCH] better way to return updated data from update boat controller

---
 server/src/controllers/boat.controllers.ts | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)

diff --git a/server/src/controllers/boat.controllers.ts b/server/src/controllers/boat.controllers.ts
index 852db6c..6423439 100644
--- a/server/src/controllers/boat.controllers.ts
+++ b/server/src/controllers/boat.controllers.ts
@@ -279,7 +279,7 @@ const updateBoatById = async (req: Request, res: Response) => {
     const newSportsArray = input.sports;
 
     if (!(newSportsArray === undefined)) {
-      //define empty array, where we store founded/not founded names of sports assigned to boat's id
+      //define empty array, where we store founded/not founded id's of sports assigned to boat's id
       var listIfNotFound = new Array();
       var listIfFound = new Array();
 
@@ -317,8 +317,6 @@ const updateBoatById = async (req: Request, res: Response) => {
           .status(404)
           .json({ success: false, error: listIfNotFound + " sportIdNotFound" });
       }
-      // help Array in order to print as response the name of the updated new sports to boat
-      var listOfNames = new Array();
       //if sports Array is with valid id's, assign them to boat; create entry (boatid, each id of given sportIds) inf BoatHasSport table
       for (let i = 0; i < listIfFound.length; i++) {
         const boatid = givenId;
@@ -327,12 +325,24 @@ const updateBoatById = async (req: Request, res: Response) => {
 
         //create new entry in boatHasBoatType
         await BoatHasSport.create(entry);
-
-        const findSportName = await (await Sport.findByPk(listIfFound[i])).name;
-        listOfNames.push(findSportName);
       }
     }
 
+    //get names of assigned sports to boat for the response message
+    // help Array in order to print as response the name of the updated + previously added new sports to boat
+    var listOfNames = new Array();
+    const findAllSportsAssignedToBoat = await BoatHasSport.findAll({
+      where: {
+        boatid: givenId,
+      },
+    });
+    for (let i = 0; i < findAllSportsAssignedToBoat.length; i++) {
+      const foundedSportName = await Sport.findByPk(
+        findAllSportsAssignedToBoat[i].sportid
+      );
+      listOfNames.push(foundedSportName.name);
+    }
+
     //we need this special case res, because sports is not an attribute assigned to Boat table, and if only sports provided as request body error happens
     // check if in the requested body only values for sports were provided
     if (Object.keys(input).length === 1 && !(input.sports === undefined)) {
-- 
GitLab