-
Notifications
You must be signed in to change notification settings - Fork 32
/
NetworkStack.swift
46 lines (36 loc) · 1.28 KB
/
NetworkStack.swift
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
import Foundation
#if canImport(AlicerceCore)
import AlicerceCore
#endif
public protocol NetworkStack: AnyObject {
associatedtype Resource
associatedtype Remote
associatedtype Response
associatedtype FetchError: Error
typealias CompletionClosure<T, E: Swift.Error> = (Result<Network.Value<T, Response>, E>) -> Void
typealias FetchCompletionClosure = CompletionClosure<Remote, FetchError>
typealias FetchResult = Result<Network.Value<Remote, Response>, FetchError>
@discardableResult
func fetch(resource: Resource, completion: @escaping FetchCompletionClosure) -> Cancelable
}
extension NetworkStack {
@discardableResult
public func fetchAndDecode<T>(
resource: Resource,
decoding: ModelDecoding<T, Remote, Response>,
completion: @escaping CompletionClosure<T, FetchAndDecodeError>
) -> Cancelable {
fetch(resource: resource) { result in
switch result {
case .success(let value):
do {
try completion(.success(value.mapValue(decoding.decode)))
} catch {
completion(.failure(.decode(error)))
}
case .failure(let error):
completion(.failure(.fetch(error)))
}
}
}
}