33 lines
1.3 KiB
Swift
33 lines
1.3 KiB
Swift
import Combine
|
|
|
|
final class ChatsMiddleware {
|
|
static let shared = ChatsMiddleware()
|
|
|
|
func middleware(state: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
|
|
switch action {
|
|
case .databaseAction(.storedChatsLoaded(let chats)):
|
|
return Just(.chatsAction(.chatsListUpdated(chats: chats)))
|
|
.eraseToAnyPublisher()
|
|
|
|
case .chatsAction(.startChat(accountJid: let accountJid, participantJid: let participantJid)):
|
|
return Future<AppAction, Never> { promise in
|
|
if let exist = state.chatsState.chats.first(where: { $0.account == accountJid && $0.participant == participantJid }) {
|
|
// open existing chat
|
|
promise(.success(.chatsAction(.chatStarted(chat: exist))))
|
|
} else {
|
|
// create new chat
|
|
promise(.success(.chatsAction(.createNewChat(accountJid: accountJid, participantJid: participantJid))))
|
|
}
|
|
}
|
|
.eraseToAnyPublisher()
|
|
|
|
case .chatsAction(.chatCreated(let chat)):
|
|
return Just(.chatsAction(.chatStarted(chat: chat)))
|
|
.eraseToAnyPublisher()
|
|
|
|
default:
|
|
return Empty().eraseToAnyPublisher()
|
|
}
|
|
}
|
|
}
|