2
0

client-call-clientstreaming.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // {{ method.name }} (Client Streaming)
  2. public class {{ .|call:protoFile,service,method }} {
  3. private var call : Call
  4. /// Create a call.
  5. fileprivate init(_ channel: Channel) {
  6. self.call = channel.makeCall("{{ .|path:protoFile,service,method }}")
  7. }
  8. // Call this to start a call.
  9. fileprivate func run(metadata:Metadata) throws -> {{ .|call:protoFile,service,method }} {
  10. let sem = DispatchSemaphore(value: 0)
  11. try self.call.start(.clientStreaming,
  12. metadata:metadata)
  13. {callResult in
  14. sem.signal()
  15. }
  16. _ = sem.wait(timeout: DispatchTime.distantFuture)
  17. return self
  18. }
  19. // Call this to send each message in the request stream.
  20. public func send(_ message: {{ method|input }}) throws {
  21. let messageData = try message.serializeProtobuf()
  22. try call.sendMessage(data:messageData)
  23. }
  24. // Call this to close the connection and wait for a response. Blocks.
  25. public func closeAndReceive() throws -> {{ method|output }} {
  26. var returnError : {{ .|clienterror:protoFile,service }}?
  27. var returnResponse : {{ method|output }}!
  28. let sem = DispatchSemaphore(value: 0)
  29. do {
  30. try call.receiveMessage() {(responseData) in
  31. if let responseData = responseData,
  32. let response = try? {{ method|output }}(protobuf:responseData) {
  33. returnResponse = response
  34. } else {
  35. returnError = {{ .|clienterror:protoFile,service }}.invalidMessageReceived
  36. }
  37. sem.signal()
  38. }
  39. try call.close(completion:{})
  40. _ = sem.wait(timeout: DispatchTime.distantFuture)
  41. } catch (let error) {
  42. throw error
  43. }
  44. if let returnError = returnError {
  45. throw returnError
  46. }
  47. return returnResponse
  48. }
  49. }