Skip to content

Instantly share code, notes, and snippets.

@bricklife
Created January 18, 2018 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bricklife/cc609df2a45d4b90c67094cc716409bf to your computer and use it in GitHub Desktop.
Save bricklife/cc609df2a45d4b90c67094cc716409bf to your computer and use it in GitHub Desktop.
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