Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions Sources/LetterboxdAPI/LetterboxdAPI+Query.swift
Original file line number Diff line number Diff line change
@@ -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<D: Decodable>(path: String, parameters: [String: String], body: String? = nil, completion: @escaping (Result<D, Error>) -> 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<D: Decodable>(path: String, parameters: [String: String], body: Data? = nil, completion: @escaping (Result<D, Error>) -> 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)
}
}
14 changes: 14 additions & 0 deletions Sources/LetterboxdAPI/LetterboxdAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,18 @@ public class LetterboxdAPI {
task.resume()
return task
}

@discardableResult
internal func processRequest(request: URLRequest, completion: @escaping (Result<Data, Error>) -> 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
}
}