feat: implemented a listen-method for the chat-service based on a Flux
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chatroom / api / ChatroomController.java
1 package de.juplo.kafka.chatroom.api;
2
3 import de.juplo.kafka.chatroom.domain.Chatroom;
4 import de.juplo.kafka.chatroom.domain.Message;
5 import lombok.RequiredArgsConstructor;
6 import org.springframework.http.MediaType;
7 import org.springframework.web.bind.annotation.*;
8 import reactor.core.publisher.Flux;
9 import reactor.core.publisher.Mono;
10
11 import java.time.Clock;
12 import java.time.Duration;
13 import java.time.LocalDateTime;
14 import java.time.LocalTime;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.UUID;
19
20
21 @RestController
22 @RequiredArgsConstructor
23 public class ChatroomController
24 {
25   private final Map<UUID, Chatroom> chatrooms = new HashMap<>();
26   private final Clock clock;
27
28
29   @PostMapping("create")
30   public Chatroom create(@RequestBody String name)
31   {
32     Chatroom chatroom = new Chatroom(UUID.randomUUID(), name);
33     chatrooms.put(chatroom.getId(), chatroom);
34     return chatroom;
35   }
36
37   @GetMapping("list")
38   public Collection<Chatroom> list()
39   {
40     return chatrooms.values();
41   }
42
43   @PutMapping("post/{chatroomId}/{username}/{messageId}")
44   public Mono<MessageTo> post(
45       @PathVariable UUID chatroomId,
46       @PathVariable String username,
47       @PathVariable UUID messageId,
48       @RequestBody String text)
49   {
50     return
51         chatrooms
52             .get(chatroomId)
53             .addMessage(
54                 messageId,
55                 LocalDateTime.now(clock),
56                 username,
57                 text)
58             .map(message -> MessageTo.from(message));
59   }
60
61   @GetMapping(
62       path = "listen/{chatroomId}",
63       produces = MediaType.TEXT_EVENT_STREAM_VALUE)
64   public Flux<Message> listen(@PathVariable UUID chatroomId)
65   {
66     return chatrooms.get(chatroomId).listen();
67   }
68 }