Wiredly enforcing uniqe-users with an exception
authorKai Moritz <kai@juplo.de>
Sun, 12 Jul 2020 13:00:39 +0000 (15:00 +0200)
committerKai Moritz <kai@juplo.de>
Sat, 24 Oct 2020 08:56:58 +0000 (10:56 +0200)
src/main/java/de/juplo/boot/data/jdbc/UserController.java

index 3087290..0aaefd5 100644 (file)
@@ -3,6 +3,7 @@ package de.juplo.boot.data.jdbc;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.dao.IncorrectResultSizeDataAccessException;
 import org.springframework.http.ResponseEntity;
 import org.springframework.transaction.annotation.Transactional;
 import org.springframework.web.bind.annotation.*;
@@ -41,8 +42,12 @@ public class UserController {
             @RequestBody String username) {
         String sanitizedUsername = UserController.sanitize(username);
         User user = new User(sanitizedUsername, LocalDateTime.now(), false);
+
+        // Triggering a unique-error for username prevents persistence
         repository.save(user);
         publisher.publishEvent(new UserEvent(this, CREATED, sanitizedUsername));
+        user = repository.findByUsername(sanitizedUsername);
+
         UriComponents uri =
             builder
                 .fromCurrentRequest()
@@ -86,4 +91,13 @@ public class UserController {
 
         return string.trim().toLowerCase();
     }
+
+    @ExceptionHandler
+    public ResponseEntity<?> incorrectResultSizeDataAccessException(
+        IncorrectResultSizeDataAccessException e
+        )
+    {
+      LOG.info("User already exists!");
+      return ResponseEntity.badRequest().build();
+    }
 }