diff --git a/Sources/LetterboxdAPI/LetterboxdAPI+Query.swift b/Sources/LetterboxdAPI/LetterboxdAPI+Query.swift new file mode 100644 index 0000000..9004251 --- /dev/null +++ b/Sources/LetterboxdAPI/LetterboxdAPI+Query.swift @@ -0,0 +1,37 @@ +// +// LetterboxdAPI+Query.swift +// LetterboxdAPI +// +// Created by Gianpiero Spinelli. +// + +import Foundation + +public extension LetterboxdAPI { + /// Generic query for any endpoint on the letterboxd APIs + /// - Parameters: + /// - path: the endpoint, eg: `/film/id` + /// - parameters: the parameters for the endpoint + /// - body: if the endpoint supports a body, please insert use it here + /// - completion: the completion of the request + func query(path: String, parameters: [String: String], body: String? = nil, completion: @escaping (Result) -> Void) { + query(path: path, parameters: parameters, body: body?.data(using: .utf8), completion: completion) + } + + /// Generic query for any endpoint on the letterboxd APIs + /// - Parameters: + /// - path: the endpoint, eg: `/film/id` + /// - parameters: the parameters for the endpoint + /// - body: if the endpoint supports a body, please insert use it here + /// - completion: the completion of the request + func query(path: String, parameters: [String: String], body: Data? = nil, completion: @escaping (Result) -> Void) { + let url = URLBuilder.url(path: path, body: body, params: parameters) + + guard let request = generateRequest(url: url, method: .get) else { + completion(.failure(LetterboxdAPIError.generatingRequest)) + return + } + + processRequest(request: request, completion: completion) + } +} diff --git a/Sources/LetterboxdAPI/LetterboxdAPI.swift b/Sources/LetterboxdAPI/LetterboxdAPI.swift index 3bcf155..26aa653 100644 --- a/Sources/LetterboxdAPI/LetterboxdAPI.swift +++ b/Sources/LetterboxdAPI/LetterboxdAPI.swift @@ -71,4 +71,18 @@ public class LetterboxdAPI { task.resume() return task } + + @discardableResult + internal func processRequest(request: URLRequest, completion: @escaping (Result) -> Void) -> URLSessionTask { + let task = URLSession.shared.dataTask(with: request) { (data, response, error) in + guard error == nil, let data = data else { + completion(.failure(error!)) + return + } + + completion(.success(data)) + } + task.resume() + return task + } }