1 package de.juplo.kafka.chat.backend.api;
3 import de.juplo.kafka.chat.backend.domain.ChatHome;
4 import de.juplo.kafka.chat.backend.domain.Chatroom;
5 import de.juplo.kafka.chat.backend.persistence.StorageStrategy;
6 import lombok.RequiredArgsConstructor;
7 import org.springframework.http.MediaType;
8 import org.springframework.http.codec.ServerSentEvent;
9 import org.springframework.web.bind.annotation.*;
10 import reactor.core.publisher.Flux;
11 import reactor.core.publisher.Mono;
13 import java.time.Clock;
14 import java.time.LocalDateTime;
15 import java.util.Optional;
16 import java.util.UUID;
17 import java.util.stream.Stream;
21 @RequiredArgsConstructor
22 public class ChatBackendController
24 private final ChatHome chatHome;
25 private final Clock clock;
26 private final StorageStrategy storageStrategy;
29 @PostMapping("create")
30 public ChatroomTo create(@RequestBody String name)
32 return ChatroomTo.from(chatHome.createChatroom(name));
36 public Stream<ChatroomTo> list()
38 return chatHome.list().map(chatroom -> ChatroomTo.from(chatroom));
41 @GetMapping("get/{chatroomId}")
42 public Optional<ChatroomTo> get(@PathVariable UUID chatroomId)
44 return chatHome.getChatroom(chatroomId).map(chatroom -> ChatroomTo.from(chatroom));
47 @PutMapping("put/{chatroomId}/{username}/{messageId}")
48 public Mono<MessageTo> put(
49 @PathVariable UUID chatroomId,
50 @PathVariable String username,
51 @PathVariable Long messageId,
52 @RequestBody String text)
56 .getChatroom(chatroomId)
57 .map(chatroom -> put(chatroom, username, messageId, text))
58 .orElseThrow(() -> new UnknownChatroomException(chatroomId));
61 public Mono<MessageTo> put(
71 LocalDateTime.now(clock),
74 .switchIfEmpty(chatroom.getMessage(username, messageId))
75 .map(message -> MessageTo.from(message));
78 @GetMapping("get/{chatroomId}/{username}/{messageId}")
79 public Mono<MessageTo> get(
80 @PathVariable UUID chatroomId,
81 @PathVariable String username,
82 @PathVariable Long messageId)
86 .getChatroom(chatroomId)
87 .map(chatroom -> get(chatroom, username, messageId))
88 .orElseThrow(() -> new UnknownChatroomException(chatroomId));
91 private Mono<MessageTo> get(
98 .getMessage(username, messageId)
99 .map(message -> MessageTo.from(message));
102 @GetMapping(path = "listen/{chatroomId}")
103 public Flux<ServerSentEvent<MessageTo>> listen(@PathVariable UUID chatroomId)
106 .getChatroom(chatroomId)
107 .map(chatroom -> listen(chatroom))
108 .orElseThrow(() -> new UnknownChatroomException(chatroomId));
111 private Flux<ServerSentEvent<MessageTo>> listen(Chatroom chatroom)
116 .map(message -> MessageTo.from(message))
120 .id(messageTo.getSerial().toString())
125 @PostMapping("/store")
128 storageStrategy.writeChatrooms(Flux.fromStream(chatHome.list()));