client-call-clientstreaming.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. try self.call.start(metadata: metadata, completion:{_ in})
  11. return self
  12. }
  13. // Call this to send each message in the request stream.
  14. public func Send(_ message: {{ method|input }}) throws {
  15. let messageData = try message.serializeProtobuf()
  16. _ = call.sendMessage(data:messageData)
  17. }
  18. // Call this to close the connection and wait for a response. Blocks.
  19. public func CloseAndReceive() throws -> {{ method|output }} {
  20. var returnError : {{ .|clienterror:protoFile,service }}?
  21. var returnMessage : {{ method|output }}!
  22. let done = NSCondition()
  23. do {
  24. try self.receiveMessage() {(responseMessage) in
  25. if let responseMessage = responseMessage {
  26. returnMessage = responseMessage
  27. } else {
  28. returnError = {{ .|clienterror:protoFile,service }}.invalidMessageReceived
  29. }
  30. done.lock()
  31. done.signal()
  32. done.unlock()
  33. }
  34. try call.close(completion:{
  35. print("closed")
  36. })
  37. done.lock()
  38. done.wait()
  39. done.unlock()
  40. } catch (let error) {
  41. print("ERROR B: \(error)")
  42. }
  43. if let returnError = returnError {
  44. throw returnError
  45. }
  46. return returnMessage
  47. }
  48. // Call this to receive a message.
  49. // The callback will be called when a message is received.
  50. // call this again from the callback to wait for another message.
  51. fileprivate func receiveMessage(callback:@escaping ({{ method|output }}?) throws -> Void)
  52. throws {
  53. try call.receiveMessage() {(data) in
  54. guard let data = data else {
  55. try callback(nil)
  56. return
  57. }
  58. guard
  59. let responseMessage = try? {{ method|output }}(protobuf:data)
  60. else {
  61. return
  62. }
  63. try callback(responseMessage)
  64. }
  65. }
  66. }