Skip to content
This repository was archived by the owner on Sep 15, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions WordPressKit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@
46ABD0E6262EEDAB00C7FF24 /* FakeInfoDictionaryObjectProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46ABD0E5262EEDAB00C7FF24 /* FakeInfoDictionaryObjectProvider.swift */; };
46ABD0EA262EEE0400C7FF24 /* AppTransportSecuritySettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46ABD0E9262EEE0400C7FF24 /* AppTransportSecuritySettingsTests.swift */; };
4A11239A2B19269A004690CF /* WordPressAPIError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A1123992B19269A004690CF /* WordPressAPIError.swift */; };
4A11239C2B1926B7004690CF /* HTTPRequestBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A11239B2B1926B7004690CF /* HTTPRequestBuilder.swift */; };
4A1DEF44293051BC00322608 /* LoggingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A1DEF43293051BC00322608 /* LoggingTests.swift */; };
4A1DEF46293051C600322608 /* LoggingTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 4A1DEF45293051C600322608 /* LoggingTests.m */; };
4A68E3CD29404181004AC3DC /* RemoteBlog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A68E3CC29404181004AC3DC /* RemoteBlog.swift */; };
Expand All @@ -150,6 +151,7 @@
4A68E3DD294070A7004AC3DC /* RemoteReaderSite.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A68E3DC294070A7004AC3DC /* RemoteReaderSite.swift */; };
4A68E3DF29407100004AC3DC /* RemoteReaderTopic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A68E3DE29407100004AC3DC /* RemoteReaderTopic.swift */; };
4A68E3E1294076C1004AC3DC /* RemoteReaderSiteInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A68E3E0294076C1004AC3DC /* RemoteReaderSiteInfo.swift */; };
4A6B4A842B26974F00802316 /* HTTPRequestBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A6B4A832B26974F00802316 /* HTTPRequestBuilderTests.swift */; };
4AA5A1A32AA68F6B00969464 /* MediaLibraryTestSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AA5A1A22AA68F6B00969464 /* MediaLibraryTestSupport.swift */; };
4AA5A1A52AA695D700969464 /* LoadMediaLibraryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AA5A1A42AA695D700969464 /* LoadMediaLibraryTests.swift */; };
57BCD3D426209D9500292CB3 /* AppTransportSecuritySettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57BCD3D326209D9500292CB3 /* AppTransportSecuritySettings.swift */; };
Expand Down Expand Up @@ -832,6 +834,7 @@
46ABD0E5262EEDAB00C7FF24 /* FakeInfoDictionaryObjectProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FakeInfoDictionaryObjectProvider.swift; sourceTree = "<group>"; };
46ABD0E9262EEE0400C7FF24 /* AppTransportSecuritySettingsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppTransportSecuritySettingsTests.swift; sourceTree = "<group>"; };
4A1123992B19269A004690CF /* WordPressAPIError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WordPressAPIError.swift; sourceTree = "<group>"; };
4A11239B2B1926B7004690CF /* HTTPRequestBuilder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPRequestBuilder.swift; sourceTree = "<group>"; };
4A1DEF43293051BC00322608 /* LoggingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoggingTests.swift; sourceTree = "<group>"; };
4A1DEF45293051C600322608 /* LoggingTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = LoggingTests.m; sourceTree = "<group>"; };
4A68E3CC29404181004AC3DC /* RemoteBlog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoteBlog.swift; sourceTree = "<group>"; };
Expand All @@ -842,6 +845,7 @@
4A68E3DC294070A7004AC3DC /* RemoteReaderSite.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoteReaderSite.swift; sourceTree = "<group>"; };
4A68E3DE29407100004AC3DC /* RemoteReaderTopic.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoteReaderTopic.swift; sourceTree = "<group>"; };
4A68E3E0294076C1004AC3DC /* RemoteReaderSiteInfo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoteReaderSiteInfo.swift; sourceTree = "<group>"; };
4A6B4A832B26974F00802316 /* HTTPRequestBuilderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPRequestBuilderTests.swift; sourceTree = "<group>"; };
4AA5A1A22AA68F6B00969464 /* MediaLibraryTestSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MediaLibraryTestSupport.swift; sourceTree = "<group>"; };
4AA5A1A42AA695D700969464 /* LoadMediaLibraryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoadMediaLibraryTests.swift; sourceTree = "<group>"; };
57BCD3D326209D9500292CB3 /* AppTransportSecuritySettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppTransportSecuritySettings.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2420,6 +2424,7 @@
93BD27791EE73944002BB00B /* WordPressOrgXMLRPCApi.swift */,
93BD277A1EE73944002BB00B /* WordPressOrgXMLRPCValidator.swift */,
93BD277B1EE73944002BB00B /* WordPressRSDParser.swift */,
4A11239B2B1926B7004690CF /* HTTPRequestBuilder.swift */,
4A1123992B19269A004690CF /* WordPressAPIError.swift */,
);
name = WordPressAPI;
Expand Down Expand Up @@ -2626,6 +2631,7 @@
803DE81028FFA9C4007D4E9C /* RemoteConfigRemoteTests.swift */,
4A1DEF43293051BC00322608 /* LoggingTests.swift */,
4A1DEF45293051C600322608 /* LoggingTests.m */,
4A6B4A832B26974F00802316 /* HTTPRequestBuilderTests.swift */,
);
path = Utilities;
sourceTree = "<group>";
Expand Down Expand Up @@ -3314,6 +3320,7 @@
7397F01A220A072500C723F3 /* ActivityServiceRemote_ApiVersion1_0.swift in Sources */,
4A68E3D429406AA0004AC3DC /* RemoteMenuItem.swift in Sources */,
8B2F4BEF24ACCC120056C08A /* RemoteReaderCard.swift in Sources */,
4A11239C2B1926B7004690CF /* HTTPRequestBuilder.swift in Sources */,
40E7FEB1220FB3B60032834E /* StatsAnnualAndMostPopularTimeInsight.swift in Sources */,
3F758FD324F6C68200BBA2FC /* AnnouncementServiceRemote.swift in Sources */,
FAB4F32324EC072700F259BA /* ReaderPostServiceRemote+Subscriptions.swift in Sources */,
Expand Down Expand Up @@ -3448,6 +3455,7 @@
8B2F4BE924ABC9DC0056C08A /* ReaderPostServiceRemote+CardsTests.swift in Sources */,
40F9880C221ACEEE00B7B369 /* StatsRemoteV2Tests.swift in Sources */,
4625BAEB253E118400C04AAD /* PageLayoutServiceRemoteTests.swift in Sources */,
4A6B4A842B26974F00802316 /* HTTPRequestBuilderTests.swift in Sources */,
465F88BF263B54EE00F4C950 /* ChecksumUtilTests.swift in Sources */,
826017001F9FD60A00533B6C /* ActivityServiceRemoteTests.swift in Sources */,
93F50A3A1F226BB600B5BEBA /* WordPressComServiceRemoteRestTests.swift in Sources */,
Expand Down
135 changes: 135 additions & 0 deletions WordPressKit/HTTPRequestBuilder.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import Foundation

final class HTTPRequestBuilder {
enum Method: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"

var allowsHTTPBody: Bool {
self == .post || self == .put || self == .patch
}
}

private var urlComponents: URLComponents
private var method: Method = .get
private var headers: [String: String] = [:]
private var bodyBuilder: ((inout URLRequest) throws -> Void)?

init(url: URL) {
assert(url.scheme == "http" || url.scheme == "https")
assert(url.host != nil)

urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)!
}

func method(_ method: Method) -> Self {
self.method = method
return self
}

func append(path: String) -> Self {
assert(!path.contains("?") && !path.contains("#"), "Path should not have query or fragment: \(path)")

var relPath = path
if relPath.hasPrefix("/") {
_ = relPath.removeFirst()
}

if urlComponents.path.hasSuffix("/") {
urlComponents.path = urlComponents.path.appending(relPath)
} else {
urlComponents.path = urlComponents.path.appending("/").appending(relPath)
}

return self
}

func header(name: String, value: String?) -> Self {
headers[name] = value
return self
}

func query(name: String, value: String?, override: Bool = false) -> Self {
append(query: [URLQueryItem(name: name, value: value)], override: override)
}
Comment on lines +55 to +57

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All the methods before this use "set" as their verb.

I think if it would be good to use it consistently, to have a homogeneous usage at call site. E.g. from

var request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/")!)
            .set(method: .post)
            .body(json: 42)

to

var request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/")!)
            .set(method: .post)
            .set(jsonBody: 42)

or

var request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/")!)
            .setMethod(.post)
            .setJSON(body: 42)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! I took the other direction: removing the "set" part, because it's redundant considering this is a "builder" type. See b52e98d.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fine by me 😄


func append(query: [URLQueryItem], override: Bool) -> Self {
urlComponents.queryItems = (urlComponents.queryItems ?? []) + query
return self
}

func body(form: [String: String]) -> Self {
headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8"
bodyBuilder = { req in
var url = URLComponents(string: "https://wordpress.com")!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be

Suggested change
var url = URLComponents(string: "https://wordpress.com")!
var url = self.urlComponents

I'm surprised https://wordpress.com/ is hardcoded here but maybe I'm missing something about the intended use? E.g., only requests to the WordPress.com API can send URL form encoded requests?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function needs a URL encoded string. I'm just using a temporary URLComponents to construct a query which is url encoded.

url.queryItems = form.map { URLQueryItem(name: $0, value: $1) }
req.httpBody = url.percentEncodedQuery?.data(using: .utf8)
}
return self
}

func body(json: Encodable, jsonEncoder: JSONEncoder = JSONEncoder()) -> Self {
body(json: {
try jsonEncoder.encode(json)
})
}

func body(json: Any) -> Self {
body(json: {
try JSONSerialization.data(withJSONObject: json)
})
}

func body(json: @escaping () throws -> Data) -> Self {
headers["Content-Type"] = "application/json; charset=utf-8"
bodyBuilder = { req in
req.httpBody = try json()
}
return self
}

func body(xml: @escaping () throws -> Data) -> Self {
headers["Content-Type"] = "application/xml; charset=utf-8"
bodyBuilder = { req in
req.httpBody = try xml()
}
return self
}

func build() throws -> URLRequest {
guard let url = urlComponents.url else {
throw URLError(.badURL)
}

var request = URLRequest(url: url)
request.httpMethod = method.rawValue

for (header, value) in headers {
request.addValue(value, forHTTPHeaderField: header)
}

if let bodyBuilder {
assert(method.allowsHTTPBody, "Can't include body in HTTP \(method.rawValue) requests")
try bodyBuilder(&request)
}

return request
}
}

extension HTTPRequestBuilder {
// FIXME: Not implemented yet
func body(xmlrpc: Any /* XMLRPCRequest */) -> Self {
body(xml: {
fatalError("To be implemented")
})
}

// FIXME: Not implemented yet
func appendXMLRPCArgument(value: Any) -> Self {
fatalError("To be implemented")
}
}
109 changes: 109 additions & 0 deletions WordPressKitTests/Utilities/HTTPRequestBuilderTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import Foundation
import XCTest

@testable import WordPressKit

class HTTPRequestBuilderTests: XCTestCase {

func testURL() throws {
try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!).build().url?.absoluteString, "https://wordpress.org")
try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.com")!).build().url?.absoluteString, "https://wordpress.com")
}

func testHTTPMethods() throws {
try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!).build().httpMethod, "GET")
XCTAssertFalse(HTTPRequestBuilder.Method.get.allowsHTTPBody)

try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!).method(.delete).build().httpMethod, "DELETE")
XCTAssertFalse(HTTPRequestBuilder.Method.delete.allowsHTTPBody)

try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!).method(.post).build().httpMethod, "POST")
XCTAssertTrue(HTTPRequestBuilder.Method.post.allowsHTTPBody)

try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!).method(.patch).build().httpMethod, "PATCH")
XCTAssertTrue(HTTPRequestBuilder.Method.patch.allowsHTTPBody)

try XCTAssertEqual(HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!).method(.put).build().httpMethod, "PUT")
XCTAssertTrue(HTTPRequestBuilder.Method.put.allowsHTTPBody)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice touch grouping the tests this way.

I don't subscribe to the "one assertion per test" rule that some tests enthusiast argue for. This kind of functional/semantic grouping strikes a good balance between not repeating the func test... cruft and having tests that point to the same behavior.

}

func testHeader() throws {
let request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.header(name: "X-Header-1", value: "Foo")
.header(name: "X-Header-2", value: "Bar")
.build()
XCTAssertEqual(request.value(forHTTPHeaderField: "X-Header-1"), "Foo")
XCTAssertEqual(request.value(forHTTPHeaderField: "X-Header-2"), "Bar")
}

func testPath() throws {
var request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.append(path: "hello/world")
.build()
XCTAssertEqual(request.url?.absoluteString, "https://wordpress.org/hello/world")

request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.append(path: "/hello/world")
.build()
XCTAssertEqual(request.url?.absoluteString, "https://wordpress.org/hello/world")

request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/hello")!)
.append(path: "world")
.build()
XCTAssertEqual(request.url?.absoluteString, "https://wordpress.org/hello/world")

request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org/hello")!)
.append(path: "/world")
.build()
XCTAssertEqual(request.url?.absoluteString, "https://wordpress.org/hello/world")
}

func testJSONBody() throws {
var request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.method(.post)
.body(json: 42)
.build()
XCTAssertTrue(request.value(forHTTPHeaderField: "Content-Type")?.contains("application/json") == true)
try XCTAssertEqual(XCTUnwrap(request.httpBodyText), "42")

request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.method(.post)
.body(json: ["foo": "bar"])
.build()
try XCTAssertEqual(XCTUnwrap(request.httpBodyText), #"{"foo":"bar"}"#)
}

func testJSONBodyWithEncodable() throws {
struct Body: Encodable {
var foo: String
}
let body = Body(foo: "bar")

let request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.method(.post)
.body(json: body)
.build()
XCTAssertTrue(request.value(forHTTPHeaderField: "Content-Type")?.contains("application/json") == true)
try XCTAssertEqual(XCTUnwrap(request.httpBodyText), #"{"foo":"bar"}"#)
}

func testFormBody() throws {
let request = try HTTPRequestBuilder(url: URL(string: "https://wordpress.org")!)
.method(.post)
.body(form: ["name": "Foo Bar"])
.build()
XCTAssertTrue(request.value(forHTTPHeaderField: "Content-Type")?.contains("application/x-www-form-urlencoded") == true)
try XCTAssertEqual(XCTUnwrap(request.httpBodyText), #"name=Foo%20Bar"#)
}

}

private extension URLRequest {
var httpBodyText: String? {
guard let data = httpBody else {
return nil
}

return String(data: data, encoding: .utf8)
}
}