client-call-unary.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /// {{ method.name }} (Unary)
  2. public class {{ .|call:file,service,method }} {
  3. private var call : Call
  4. /// Create a call.
  5. fileprivate init(_ channel: Channel) {
  6. self.call = channel.makeCall("{{ .|path:file,service,method }}")
  7. }
  8. /// Run the call. Blocks until the reply is received.
  9. fileprivate func run(request: {{ method|input }},
  10. metadata: Metadata) throws -> {{ method|output }} {
  11. let sem = DispatchSemaphore(value: 0)
  12. var returnCallResult : CallResult!
  13. var returnResponse : {{ method|output }}?
  14. _ = try start(request:request, metadata:metadata) {response, callResult in
  15. returnResponse = response
  16. returnCallResult = callResult
  17. sem.signal()
  18. }
  19. _ = sem.wait(timeout: DispatchTime.distantFuture)
  20. if let returnResponse = returnResponse {
  21. return returnResponse
  22. } else {
  23. throw {{ .|clienterror:file,service }}.error(c: returnCallResult)
  24. }
  25. }
  26. /// Start the call. Nonblocking.
  27. fileprivate func start(request: {{ method|input }},
  28. metadata: Metadata,
  29. completion: @escaping ({{ method|output }}?, CallResult)->())
  30. throws -> {{ .|call:file,service,method }} {
  31. let requestData = try request.serializedData()
  32. try call.start(.unary,
  33. metadata:metadata,
  34. message:requestData)
  35. {(callResult) in
  36. if let responseData = callResult.resultData,
  37. let response = try? {{ method|output }}(serializedData:responseData) {
  38. completion(response, callResult)
  39. } else {
  40. completion(nil, callResult)
  41. }
  42. }
  43. return self
  44. }
  45. }