-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GutenbergNetworking.swift
73 lines (60 loc) · 2.61 KB
/
GutenbergNetworking.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import Alamofire
import WordPressKit
struct GutenbergNetworkRequest {
typealias CompletionHandler = (Swift.Result<Any, NSError>) -> Void
private let path: String
private unowned let blog: Blog
init(path: String, blog: Blog) {
self.path = path
self.blog = blog
}
func request(completion: @escaping CompletionHandler) {
if blog.isAccessibleThroughWPCom(), let dotComID = blog.dotComID {
dotComRequest(with: dotComID, completion: completion)
} else {
selfHostedRequest(completion: completion)
}
}
// MARK: - dotCom
private func dotComRequest(with dotComID: NSNumber, completion: @escaping CompletionHandler) {
blog.wordPressComRestApi()?.GET(dotComPath(with: dotComID), parameters: nil, success: { (response, httpResponse) in
completion(.success(response))
}, failure: { (error, httpResponse) in
completion(.failure(error.nsError(with: httpResponse)))
})
}
private func dotComPath(with dotComID: NSNumber) -> String {
return path.replacingOccurrences(of: "/wp/v2/", with: "/wp/v2/sites/\(dotComID)/")
}
// MARK: - Self-Hosed
private func selfHostedRequest(completion: @escaping CompletionHandler) {
performSelfHostedRequest(completion: completion)
}
private func performSelfHostedRequest(completion: @escaping CompletionHandler) {
guard let api = blog.wordPressOrgRestApi else {
completion(.failure(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil)))
return
}
api.GET(path, parameters: nil) { (result, httpResponse) in
switch result {
case .success(let response):
completion(.success(response))
case .failure(let error):
completion(.failure(error as NSError))
}
}
}
private var selfHostedPath: String {
let removedEditContext = path.replacingOccurrences(of: "context=edit", with: "context=view")
return "wp-json\(removedEditContext)"
}
}
/// Helper to get an error instance with the real HTTP Status code, taken from the response object.
/// This is needed since AlamoFire will return code: 7 for any error.
private extension Error {
func nsError(with response: HTTPURLResponse?) -> NSError {
let errorCode = response?.statusCode ?? URLError.Code.unknown.rawValue
let code = URLError.Code(rawValue: errorCode)
return URLError(code, userInfo: [NSLocalizedDescriptionKey: localizedDescription]) as NSError
}
}