Created
January 18, 2018 13:55
-
-
Save bricklife/cc609df2a45d4b90c67094cc716409bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import JSONRPCKit | |
struct CastError<ExpectedType>: Error { | |
let actualValue: Any | |
let expectedType: ExpectedType.Type | |
} | |
struct Subtract: JSONRPCKit.Request { | |
typealias Response = Int | |
let minuend: Int | |
let subtrahend: Int | |
var method: String { | |
return "subtract" | |
} | |
var parameters: Any? { | |
return [minuend, subtrahend] | |
} | |
func response(from resultObject: Any) throws -> Response { | |
if let response = resultObject as? Response { | |
return response | |
} else { | |
throw CastError(actualValue: resultObject, expectedType: Response.self) | |
} | |
} | |
} | |
let batchFactory = BatchFactory() | |
let batch = batchFactory.create(Subtract(minuend: 10, subtrahend: 5)) | |
print(batch.requestObject) | |
let url = URL(string: "https://jsonrpckit-demo.appspot.com/")! | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
var headers = request.allHTTPHeaderFields ?? [:] | |
headers["Content-Type"] = "application/json" | |
request.allHTTPHeaderFields = headers | |
request.httpBody = try? JSONSerialization.data(withJSONObject: batch.requestObject, options: []) | |
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in | |
if let data = data { | |
let json = try! JSONSerialization.jsonObject(with: data, options: []) | |
print(json) | |
let response = try! batch.responses(from: json) | |
print(response) | |
} | |
if let error = error { | |
print(error) | |
} | |
} | |
task.resume() | |
while (true) {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment