Reputation: 33
I'm using JSONRPCKit lib, so there's final request contains that Request
let request1 = RPCRequest(params: SomeParams)
let batch1 = batchFactory.create(request1)
let httpRequest1 = MyServiceRequest(batch: batch1)
Session.send(httpRequest1){ result in
switch result {
case .success(let auth):
let gson = JSON(auth)
print(gson)
case .failure(let error):
print("Error: ", error)
}
}
I have to make a lot of requests like this. So i want to make it Generic to keep reuse it not typing everything again.
Could you please help me?
Upvotes: 0
Views: 128
Reputation: 21144
Just create a generic method which wraps these code inside something like this,
func sendRequest<T>(request: RCPRequest,
mapping: @escaping (JSON) throws -> T,
completion: @escaping (T?, Error?) -> Void) {
let batch = batchFactory.create(request)
let httpRequest = MyServiceRequest(batch: batch)
Session.send(httpRequest){ result in
switch result {
case .success(let auth):
let gson = JSON(auth)
do {
let output = try mapping(gson)
completion(output, nil)
} catch {
completion(nil, error)
}
case .failure(let error):
completion(nil, error)
}
}
}
Then call it like this,
let request1 = RPCRequest(params: SomeParams)
sendRequest(request: request1,
mapping: { json in
// convert from json to the custom type T, whatever T is
// throw error if something isnt right in json
},
completion: { output, error in
if let output = output {
}
})
Upvotes: 1