How to make a Data representation from a list of parameters for a POST method (Swift)

44 Views Asked by At

Say I have the following API Service:

enum HttpMethod: Equatable {
    case get([URLQueryItem])
    case put(Data?)
    case post(Data?)

    var name: String {
        switch self {
        case .get: return "GET"
        case .put: return "PUT"
        case .post: return "POST"
        }
    }
}

struct Request<Response> {
    let url: URL
    let method: HttpMethod
    var headers: [String: String] = [:]
}

extension Request {
    var urlRequest: URLRequest {
        var request = URLRequest(url: url)

        switch method {
        case .post(let data), .put(let data):
            request.httpBody = data
        case let .get(queryItems):
            var components = URLComponents(url: url, resolvingAgainstBaseURL: false)
            components?.queryItems = queryItems
            guard let url = components?.url else {
                preconditionFailure("Couldn't create a url from components...")
            }
            request = URLRequest(url: url)
        default:
            break
        }

        request.allHTTPHeaderFields = headers
        request.httpMethod = method.name
        return request
    }
}

How can I compose a Data representation from a list of parameters that I can POST?

extension Request {
    static func postEvent(type: String, title:String, tableId:Int? = nil, params: [String:Any]?) -> Self {
        Request(
            url: URL(string: NetworkingConstants.EVENTS)!,
            method: .post(
                // WHAT GOES HERE?
                // How to compose Data representation JSON?
            )
        )
    }
}
0

There are 0 best solutions below