Skip to content

Instantly share code, notes, and snippets.

@dkulundzic
Last active February 2, 2023 12:49
Show Gist options
  • Save dkulundzic/bb6039c6861056e26a101ca3bb37cf90 to your computer and use it in GitHub Desktop.
Save dkulundzic/bb6039c6861056e26a101ca3bb37cf90 to your computer and use it in GitHub Desktop.
A testable, Promise based example network service
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