added request builder
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
This commit is contained in:
parent
3314304b46
commit
13de040621
55
EmployeeDirectory/Classes/RequestBuilder.swift
Normal file
55
EmployeeDirectory/Classes/RequestBuilder.swift
Normal file
@ -0,0 +1,55 @@
|
||||
//
|
||||
// RequestBuilder.swift
|
||||
// EmployeeDirectory
|
||||
//
|
||||
// Created by Matt Bruce on 1/21/25.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Enum representing HTTP methods
|
||||
public enum HTTPMethod: String {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
case put = "PUT"
|
||||
case delete = "DELETE"
|
||||
case patch = "PATCH"
|
||||
case head = "HEAD"
|
||||
case options = "OPTIONS"
|
||||
}
|
||||
|
||||
/// A utility for constructing HTTP requests
|
||||
public struct RequestBuilder {
|
||||
private var url: URL
|
||||
private var method: HTTPMethod
|
||||
private var headers: [String: String] = [:]
|
||||
private var body: Data?
|
||||
|
||||
public init(url: URL, method: HTTPMethod = .get) {
|
||||
self.url = url
|
||||
self.method = method
|
||||
}
|
||||
|
||||
/// Add a header to the request
|
||||
@discardableResult
|
||||
public mutating func addHeader(key: String, value: String) -> Self {
|
||||
headers[key] = value
|
||||
return self
|
||||
}
|
||||
|
||||
/// Set the body of the request
|
||||
@discardableResult
|
||||
public mutating func setBody(_ data: Data?) -> Self {
|
||||
body = data
|
||||
return self
|
||||
}
|
||||
|
||||
/// Build the `URLRequest`
|
||||
public func build() -> URLRequest {
|
||||
var request = URLRequest(url: url)
|
||||
request.httpMethod = method.rawValue
|
||||
request.allHTTPHeaderFields = headers
|
||||
request.httpBody = body
|
||||
return request
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user