client-call-clientstreaming.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 start(metadata:Metadata, completion:@escaping (CallResult)->())
  10. throws -> {{ .|call:protoFile,service,method }} {
  11. try self.call.start(.clientStreaming, metadata:metadata, completion:completion)
  12. return self
  13. }
  14. /// Call this to send each message in the request stream.
  15. public func send(_ message: {{ method|input }}) throws {
  16. let messageData = try message.serializeProtobuf()
  17. try call.sendMessage(data:messageData)
  18. }
  19. /// Call this to close the connection and wait for a response. Blocking.
  20. public func closeAndReceive() throws -> {{ method|output }} {
  21. var returnError : {{ .|clienterror:protoFile,service }}?
  22. var returnResponse : {{ method|output }}!
  23. let sem = DispatchSemaphore(value: 0)
  24. do {
  25. try call.receiveMessage() {(responseData) in
  26. if let responseData = responseData,
  27. let response = try? {{ method|output }}(protobuf:responseData) {
  28. returnResponse = response
  29. } else {
  30. returnError = {{ .|clienterror:protoFile,service }}.invalidMessageReceived
  31. }
  32. sem.signal()
  33. }
  34. try call.close(completion:{})
  35. _ = sem.wait(timeout: DispatchTime.distantFuture)
  36. } catch (let error) {
  37. throw error
  38. }
  39. if let returnError = returnError {
  40. throw returnError
  41. }
  42. return returnResponse
  43. }
  44. /// Call this to close the connection and wait for a response. Nonblocking.
  45. public func closeAndReceive(completion:@escaping ({{ method|output }}?, {{ .|clienterror:protoFile,service }}?)->())
  46. throws {
  47. do {
  48. try call.receiveMessage() {(responseData) in
  49. if let responseData = responseData,
  50. let response = try? {{ method|output }}(protobuf:responseData) {
  51. completion(response, nil)
  52. } else {
  53. completion(nil, {{ .|clienterror:protoFile,service }}.invalidMessageReceived)
  54. }
  55. }
  56. try call.close(completion:{})
  57. } catch (let error) {
  58. throw error
  59. }
  60. }
  61. }