This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathJetpackProxyServiceRemote.swift
More file actions
58 lines (52 loc) · 2.5 KB
/
Copy pathJetpackProxyServiceRemote.swift
File metadata and controls
58 lines (52 loc) · 2.5 KB
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
/// Encapsulates Jetpack Proxy requests.
public class JetpackProxyServiceRemote: ServiceRemoteWordPressComREST {
/// Represents the most common HTTP methods for the proxied request.
public enum DotComMethod: String {
case get
case post
case put
case delete
}
/// Sends a proxied request to a Jetpack-connected site through the Jetpack Proxy API.
/// The proxy API expects the client to be authenticated with a WordPress.com account.
///
/// - Parameters:
/// - siteID: The dotcom ID of the Jetpack-connected site.
/// - path: The request endpoint to be proxied.
/// - method: The HTTP method for the proxied request.
/// - parameters: The request parameter for the proxied request. Defaults to empty.
/// - locale: The user locale, if any. Defaults to nil.
/// - completion: Closure called after the request completes.
/// - Returns: A Progress object, which can be used to cancel the request if needed.
@discardableResult
public func proxyRequest(for siteID: Int,
path: String,
method: DotComMethod,
parameters: [String: AnyHashable] = [:],
locale: String? = nil,
completion: @escaping (Result<Any, Error>) -> Void) -> Progress? {
let urlString = self.path(forEndpoint: "jetpack-blogs/\(siteID)/rest-api", withVersion: ._1_1)
// Construct the request parameters to be forwarded to the actual endpoint.
var requestParams: [String: AnyHashable] = [
"json": "true",
"path": "\(path)&_method=\(method.rawValue)"
]
// The parameters need to be encoded into a JSON string.
if !parameters.isEmpty,
let data = try? JSONSerialization.data(withJSONObject: parameters, options: []),
let jsonString = String(data: data, encoding: .utf8) {
// Use "query" for the body parameters if the method is GET. Otherwise, always use "body".
let bodyParameterKey = (method == .get ? "query" : "body")
requestParams[bodyParameterKey] = jsonString
}
if let locale,
!locale.isEmpty {
requestParams["locale"] = locale
}
return wordPressComRESTAPI.post(urlString, parameters: requestParams) { response, _ in
completion(.success(response))
} failure: { error, _ in
completion(.failure(error))
}
}
}