From 8c65289b800c0804cf5de4211d05742406d38568 Mon Sep 17 00:00:00 2001
From: Mathieu Vonlanthen <Mathieu.Vonlanthen@unige.ch>
Date: Fri, 17 Feb 2023 15:11:25 +0100
Subject: [PATCH] refactor(Relation3TiersController): use
 existsByIdOrThrowException in update method

---
 .../controller/Relation3TiersController.java  | 22 ++++++++++---------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/solidify-controller/src/main/java/ch/unige/solidify/controller/Relation3TiersController.java b/solidify-controller/src/main/java/ch/unige/solidify/controller/Relation3TiersController.java
index fc03e1e06..3652cd890 100644
--- a/solidify-controller/src/main/java/ch/unige/solidify/controller/Relation3TiersController.java
+++ b/solidify-controller/src/main/java/ch/unige/solidify/controller/Relation3TiersController.java
@@ -378,17 +378,19 @@ public abstract class Relation3TiersController<T extends Resource, V extends Res
    */
   @PatchMapping(SolidifyConstants.URL_ID)
   public HttpEntity<List<J>> update(@PathVariable String parentid, @PathVariable String id, @RequestBody J joinResource) {
-    V childItem = this.childItemService.findOne(id);
-    List<J> joinResources = this.relationItemService.findAllRelations(parentid, childItem.getResId());
-    final List<J> list = new ArrayList<>();
-    for (final J existingJoinResource : joinResources) {
-      J updatedJoinResource = this.relationItemService.completeJoinResourceRelations(joinResource, parentid, id,
-              this.relationItemService.getGrandChildResource(existingJoinResource).getResId());
-      final J savedJoinResource = this.relationItemService.saveRelation(updatedJoinResource);
-      list.add(savedJoinResource);
+    // Check if parents exist
+    this.itemService.existsByIdOrThrowException(parentid);
+    this.childItemService.existsByIdOrThrowException(id);
+
+    final List<J> savedRelationsList = new ArrayList<>();
+    for (final J existingJoinResource : this.relationItemService.findAllRelations(parentid, id)) {
+      final String grandChildId = this.relationItemService.getGrandChildResource(existingJoinResource).getResId();
+      final J updatedJoinResource = this.relationItemService.completeJoinResourceRelations(joinResource, parentid, id, grandChildId);
+      final J savedRelation = this.relationItemService.saveRelation(updatedJoinResource);
+      savedRelationsList.add(savedRelation);
     }
-    if (!list.isEmpty()) {
-      return new ResponseEntity<>(list, HttpStatus.CREATED);
+    if (!savedRelationsList.isEmpty()) {
+      return new ResponseEntity<>(savedRelationsList, HttpStatus.CREATED);
     }
     return new ResponseEntity<>(HttpStatus.OK);
   }
-- 
GitLab