|
| 1 | +// |
| 2 | +// NetworkClient.swift |
| 3 | +// Magic |
| 4 | +// |
| 5 | +// Created by Jerry Liu on 2/09/20. |
| 6 | +// Copyright © 2020 Magic Labs Inc. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import Foundation |
| 10 | +import PromiseKit |
| 11 | + |
| 12 | +/// A base networking class that can send http requests |
| 13 | +public class NetworkClient { |
| 14 | + |
| 15 | + /// Various errors that may occur while processing Web3 requests |
| 16 | + public enum Error: Swift.Error { |
| 17 | + /// The response did not include expected results |
| 18 | + case unexpectedResponse(Swift.Error?) |
| 19 | + /// The server returned an unexpected response code |
| 20 | + case invalidResponseCode |
| 21 | + } |
| 22 | + |
| 23 | + /// Internal queue for handling requests |
| 24 | + let queue: DispatchQueue |
| 25 | + |
| 26 | + /// Internal URLSession for this Web3Provider's RPC requests |
| 27 | + let session: URLSession = URLSession(configuration: .default) |
| 28 | + |
| 29 | + /// JSONEncoder for encoding RPCRequests |
| 30 | + let encoder = JSONEncoder() |
| 31 | + |
| 32 | + /// JSONDecoder for parsing RPCResponses |
| 33 | + let decoder = JSONDecoder() |
| 34 | + |
| 35 | + /// HTTP headers to add to all requests |
| 36 | + public var headers = [ |
| 37 | + "Content-Type": "application/json" |
| 38 | + ] |
| 39 | + |
| 40 | + init() { |
| 41 | + self.queue = DispatchQueue(label: "MagicHttpProvider", attributes: .concurrent) |
| 42 | + } |
| 43 | + |
| 44 | + /// Encode an object with or without a prefix into data |
| 45 | + /// |
| 46 | + /// - Parameters: |
| 47 | + /// - body: Object to encode. Must be Encodable. |
| 48 | + /// - prefix: Optional string to prefix the body with |
| 49 | + /// - Returns: Promise resolving with the encoded Data |
| 50 | + func encode<T: Encodable>(body: T, withPrefix prefix: String? = nil) -> Promise<Data> { |
| 51 | + return Promise { resolver in |
| 52 | + queue.async { |
| 53 | + do { |
| 54 | + let encoded: Data |
| 55 | + if let prefix = prefix { |
| 56 | + encoded = try self.encoder.encode([prefix: body]) |
| 57 | + } else { |
| 58 | + encoded = try self.encoder.encode(body) |
| 59 | + } |
| 60 | + resolver.fulfill(encoded) |
| 61 | + } catch { |
| 62 | + resolver.reject(error) |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + /// Sends a basic http request. |
| 69 | + /// This method will create a URLRequest, and then run a URLSessionDataTask with the URLRequest. |
| 70 | + /// Once a response is received, the response will be validated for data and a valid status code |
| 71 | + /// before calling the callback with the resulting data or error. |
| 72 | + /// |
| 73 | + /// - Parameters: |
| 74 | + /// - url: url for the request |
| 75 | + /// - method: HTTP method to use |
| 76 | + /// - body: Optional request body to include |
| 77 | + /// - Returns: Promise resolving with Data from the response if it's successful |
| 78 | + func postRequest(url: URL, method: String, body: Data?) -> Promise<Data> { |
| 79 | + return Promise { resolver in |
| 80 | + queue.async { |
| 81 | + var req = URLRequest(url: url) |
| 82 | + req.httpMethod = method |
| 83 | + req.httpBody = body |
| 84 | + |
| 85 | + // Add default headers |
| 86 | + for (k, v) in self.headers { |
| 87 | + req.addValue(v, forHTTPHeaderField: k) |
| 88 | + } |
| 89 | + |
| 90 | + // Create the URLSessionTask |
| 91 | + let task = self.session.dataTask(with: req) { data, urlResponse, error in |
| 92 | + guard let urlResponse = urlResponse as? HTTPURLResponse, let data = data, error == nil else { |
| 93 | + resolver.reject(Error.unexpectedResponse(error)) |
| 94 | + return |
| 95 | + } |
| 96 | + |
| 97 | + guard urlResponse.statusCode >= 200 && urlResponse.statusCode < 300 else { |
| 98 | + resolver.reject(Error.invalidResponseCode) |
| 99 | + return |
| 100 | + } |
| 101 | + |
| 102 | + resolver.fulfill(data) |
| 103 | + } |
| 104 | + task.resume() |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | +} |
0 commit comments