block-employee-directory/EmployeeDirectory/Classes/RequestBuilder.swift
Matt Bruce 13de040621 added request builder
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2025-01-21 11:16:16 -06:00

56 lines
1.3 KiB
Swift

//
// 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
}
}