forked from Spurthi-Ravula/Group2-Student-Info-Exchange-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatRoomService.java
57 lines (46 loc) · 1.73 KB
/
ChatRoomService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.example.SMS.liveChat.chatroom;
import com.example.SMS.entity.ChatRoom;
import com.example.SMS.entity.User;
import com.example.SMS.repository.ChatRoomRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class ChatRoomService {
private final ChatRoomRepository chatRoomRepository;
public Optional<String> getChatRoomId(
User senderId,
User recipientId,
boolean createNewRoomIfNotExists
) {
return chatRoomRepository
.findBySenderIdAndRecipientId(senderId, recipientId)
.map(ChatRoom::getChatId)
.or(() -> {
if(createNewRoomIfNotExists) {
var chatId = createChatId(senderId, recipientId);
return Optional.of(chatId);
}
return Optional.empty();
});
}
private String createChatId(User senderId, User recipientId) {
var chatId = String.format("%s_%s", senderId.getEmail(), recipientId.getEmail());
ChatRoom senderRecipient = ChatRoom
.builder()
.chatId(chatId)
.senderId(senderId)
.recipientId(recipientId)
.build();
ChatRoom recipientSender = ChatRoom
.builder()
.chatId(chatId)
.senderId(recipientId)
.recipientId(senderId)
.build();
chatRoomRepository.save(senderRecipient);
chatRoomRepository.save(recipientSender);
return chatId;
}
}