Last active
February 2, 2023 12:49
-
-
Save dkulundzic/bb6039c6861056e26a101ca3bb37cf90 to your computer and use it in GitHub Desktop.
A testable, Promise based example network service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol ChatNetworkService { | |
func loadMessages(bookingId: String) -> Promise<[ChatMessage]> | |
func sendMessage(_ message: String, bookingId: String) -> Promise<ChatMessage> | |
} | |
public final class DefaultChatNetworkService { | |
public init() { } | |
} | |
extension ChatNetworkService: ChatNetworkService { | |
public func loadMessages(bookingId: String) -> Promise<[ChatMessage]> { | |
Promise { fullfill, reject in | |
Networking.session | |
.request(resource: ChatResource.getMessages(bookingId: bookingId)) | |
.validate() | |
.responseDecodable( | |
decoder: JSONDecoder.default | |
) { (response: DataResponse<ApiResponseContainer<[ChatMessage]>, AFError>) in | |
switch response.result { | |
case .success(let container): | |
fullfill(container.data) | |
case .failure(let error): | |
reject(error) | |
} | |
} | |
} | |
} | |
public func sendMessage(_ message: String, bookingId: String) -> Promise<ChatMessage> { | |
Promise { fullfill, reject in | |
Networking.session | |
.request( | |
resource: ChatResource.postMessage(bookingId: bookingId), | |
parameters: ChatMessageDTO(content: message) | |
) | |
.validate() | |
.responseDecodable( | |
decoder: JSONDecoder.default | |
) { (response: DataResponse<ApiResponseContainer<ChatMessage>, AFError>) in | |
switch response.result { | |
case .success(let container): | |
fullfill(container.data) | |
case .failure(let error): | |
reject(error) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment