refactor: Added success- and failure-callbacks to `StorageStrategy`
authorKai Moritz <kai@juplo.de>
Sat, 3 Feb 2024 21:44:02 +0000 (22:44 +0100)
committerKai Moritz <kai@juplo.de>
Mon, 19 Feb 2024 07:30:18 +0000 (08:30 +0100)
src/main/java/de/juplo/kafka/chat/backend/implementation/StorageStrategy.java

index 24fd15f..8f91ad0 100644 (file)
@@ -3,13 +3,19 @@ package de.juplo.kafka.chat.backend.implementation;
 import de.juplo.kafka.chat.backend.domain.ChatHomeService;
 import de.juplo.kafka.chat.backend.domain.ChatRoomInfo;
 import de.juplo.kafka.chat.backend.domain.Message;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import reactor.core.publisher.Flux;
 
 import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
 
 
 public interface StorageStrategy
 {
+  Logger log = LoggerFactory.getLogger(StorageStrategy.class.getCanonicalName());
+
   default void write(ChatHomeService chatHomeService)
   {
     writeChatRoomInfo(
@@ -20,11 +26,38 @@ public interface StorageStrategy
                     chatRoomInfo.getId(),
                     chatHomeService
                         .getChatRoomData(chatRoomInfo.getId())
-                        .flatMapMany(chatRoomData -> chatRoomData.getMessages()))));
+                        .flatMapMany(chatRoomData -> chatRoomData.getMessages()),
+                    this::logSuccessChatRoom,
+                    this::logFailureChatRoom)));
   }
 
   void writeChatRoomInfo(Flux<ChatRoomInfo> chatRoomInfoFlux);
   Flux<ChatRoomInfo> readChatRoomInfo();
+  default void writeChatRoomData(
+      UUID chatRoomId,
+      Flux<Message> messageFlux,
+      ChatRoomWrittenSuccessCallback successCallback,
+      ChatRoomWrittenFailureCallback failureCallback)
+  {
+    writeChatRoomData(
+        chatRoomId,
+        messageFlux
+            .doOnComplete(() -> successCallback.accept(chatRoomId))
+            .doOnError(throwable -> failureCallback.accept(chatRoomId, throwable)));
+  }
   void writeChatRoomData(UUID chatRoomId, Flux<Message> messageFlux);
   Flux<Message> readChatRoomData(UUID chatRoomId);
+
+  interface ChatRoomWrittenSuccessCallback extends Consumer<UUID> {}
+  interface ChatRoomWrittenFailureCallback extends BiConsumer<UUID, Throwable> {}
+
+  default void logSuccessChatRoom(UUID chatRoomId)
+  {
+    log.info("Successfully stored chat-room {}", chatRoomId);
+  }
+
+  default void logFailureChatRoom(UUID chatRoomId, Throwable throwable)
+  {
+    log.error("Could not store chat-room {}: {}", chatRoomId, throwable);
+  }
 }