Skip to content

Commit 9e8786e

Browse files
authored
Merge pull request #5 from gianpispi/query
Added a `query` function for not yet supported endpoints
2 parents 0c5b41c + ab83549 commit 9e8786e

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//
2+
// LetterboxdAPI+Query.swift
3+
// LetterboxdAPI
4+
//
5+
// Created by Gianpiero Spinelli.
6+
//
7+
8+
import Foundation
9+
10+
public extension LetterboxdAPI {
11+
/// Generic query for any endpoint on the letterboxd APIs
12+
/// - Parameters:
13+
/// - path: the endpoint, eg: `/film/id`
14+
/// - parameters: the parameters for the endpoint
15+
/// - body: if the endpoint supports a body, please insert use it here
16+
/// - completion: the completion of the request
17+
func query<D: Decodable>(path: String, parameters: [String: String], body: String? = nil, completion: @escaping (Result<D, Error>) -> Void) {
18+
query(path: path, parameters: parameters, body: body?.data(using: .utf8), completion: completion)
19+
}
20+
21+
/// Generic query for any endpoint on the letterboxd APIs
22+
/// - Parameters:
23+
/// - path: the endpoint, eg: `/film/id`
24+
/// - parameters: the parameters for the endpoint
25+
/// - body: if the endpoint supports a body, please insert use it here
26+
/// - completion: the completion of the request
27+
func query<D: Decodable>(path: String, parameters: [String: String], body: Data? = nil, completion: @escaping (Result<D, Error>) -> Void) {
28+
let url = URLBuilder.url(path: path, body: body, params: parameters)
29+
30+
guard let request = generateRequest(url: url, method: .get) else {
31+
completion(.failure(LetterboxdAPIError.generatingRequest))
32+
return
33+
}
34+
35+
processRequest(request: request, completion: completion)
36+
}
37+
}

Sources/LetterboxdAPI/LetterboxdAPI.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,18 @@ public class LetterboxdAPI {
7171
task.resume()
7272
return task
7373
}
74+
75+
@discardableResult
76+
internal func processRequest(request: URLRequest, completion: @escaping (Result<Data, Error>) -> Void) -> URLSessionTask {
77+
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
78+
guard error == nil, let data = data else {
79+
completion(.failure(error!))
80+
return
81+
}
82+
83+
completion(.success(data))
84+
}
85+
task.resume()
86+
return task
87+
}
7488
}

0 commit comments

Comments
 (0)