-
Notifications
You must be signed in to change notification settings - Fork 16
Add HTTPRequestBuilder #657
Changes from all commits
ce52f1d
577ebd4
b52e98d
c70478b
e27fe43
fbbbd0c
4bb8360
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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) | ||||||
| } | ||||||
|
|
||||||
| 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")! | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this be
Suggested change
I'm surprised
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||||||
| 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") | ||||||
| } | ||||||
| } | ||||||
| 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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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) | ||
| } | ||
| } | ||
There was a problem hiding this comment.
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
to
or
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fine by me 😄