refactor: Streamlined the API of the services
[demos/kafka/chat] / src / main / java / de / juplo / kafka / chat / backend / domain / ChatHome.java
1 package de.juplo.kafka.chat.backend.domain;
2
3 import lombok.extern.slf4j.Slf4j;
4 import reactor.core.publisher.Flux;
5 import reactor.core.publisher.Mono;
6
7 import java.util.*;
8
9
10 @Slf4j
11 public class ChatHome
12 {
13   private final Map<UUID, ChatRoom> chatrooms;
14   private final ChatHomeService service;
15
16   public ChatHome(ChatHomeService service, Flux<ChatRoom> chatroomFlux)
17   {
18     log.debug("Creating ChatHome with factory: {}", service);
19     this.service = service;
20     this.chatrooms = new HashMap<>();
21     chatroomFlux.subscribe(chatroom -> chatrooms.put(chatroom.getId(), chatroom));
22   }
23
24   public Mono<ChatRoom> createChatroom(String name)
25   {
26     ChatRoom chatroom = service.createChatroom(UUID.randomUUID(), name);
27     chatrooms.put(chatroom.getId(), chatroom);
28     return Mono.justOrEmpty(chatroom);
29   }
30
31   public Mono<ChatRoom> getChatroom(UUID id)
32   {
33     return Mono
34         .justOrEmpty(chatrooms.get(id))
35         .or(Mono.error(() -> new UnknownChatroomException(id)));
36   }
37
38   public Flux<ChatRoom> list()
39   {
40     return Flux.fromStream(chatrooms.values().stream());
41   }
42 }