Skip to content

Instantly share code, notes, and snippets.

@kien-hoang
Created January 18, 2023 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kien-hoang/65f95ddf93d52ccfb56aa5b2833bb444 to your computer and use it in GitHub Desktop.
Save kien-hoang/65f95ddf93d52ccfb56aa5b2833bb444 to your computer and use it in GitHub Desktop.
builder-pattern.swift
final class URLRequestBuilder {
private var components = URLComponents()
private var httpMethod: String = "GET"
private var headers: [String: String] = [:]
private var body: [String: Any]?
// MARK: - Lifecycle
init(baseUrl: String = "https://api.themoviedb.org") {
components = URLComponents(string: baseUrl)!
}
// MARK: - Construction Classes
func setPath(_ path: String) -> URLRequestBuilder {
var path = path
if !path.hasPrefix("/") {
path = "/" + path
}
components.path = path
return self
}
func setQueryItems(_ queryItems: [String: String]) -> URLRequestBuilder {
components.queryItems = queryItems.map { key, value in
URLQueryItem(name: key, value: "\(value)")
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
return self
}
func setHTTPMethod(_ method: String) -> URLRequestBuilder {
httpMethod = method
return self
}
func setHeaders(_ headers: [String: String]) -> URLRequestBuilder {
self.headers = headers
return self
}
func setBody(_ body: [String: Any]) -> URLRequestBuilder {
self.body = body
return self
}
// MARK: - Builder Pattern
func build() -> URLRequest? {
guard let url = components.url else { return nil }
var request = URLRequest(url: url)
request.httpMethod = httpMethod
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
headers.forEach { request.addValue($0.value, forHTTPHeaderField: $0.key) }
if let body = body {
let jsonData = try? JSONSerialization.data(withJSONObject: body, options: [])
request.httpBody = jsonData
}
return request
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment