EchoProvider.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright 2018, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import EchoModel
  17. import Foundation
  18. import GRPC
  19. import NIO
  20. public class EchoProvider: Echo_EchoProvider {
  21. public init() {}
  22. public func get(
  23. request: Echo_EchoRequest,
  24. context: StatusOnlyCallContext
  25. ) -> EventLoopFuture<Echo_EchoResponse> {
  26. let response = Echo_EchoResponse.with {
  27. $0.text = "Swift echo get: " + request.text
  28. }
  29. return context.eventLoop.makeSucceededFuture(response)
  30. }
  31. public func expand(
  32. request: Echo_EchoRequest,
  33. context: StreamingResponseCallContext<Echo_EchoResponse>
  34. ) -> EventLoopFuture<GRPCStatus> {
  35. let responses = request.text.components(separatedBy: " ").lazy.enumerated().map { i, part in
  36. Echo_EchoResponse.with {
  37. $0.text = "Swift echo expand (\(i)): \(part)"
  38. }
  39. }
  40. context.sendResponses(responses, promise: nil)
  41. return context.eventLoop.makeSucceededFuture(.ok)
  42. }
  43. public func collect(
  44. context: UnaryResponseCallContext<Echo_EchoResponse>
  45. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  46. var parts: [String] = []
  47. return context.eventLoop.makeSucceededFuture({ event in
  48. switch event {
  49. case let .message(message):
  50. parts.append(message.text)
  51. case .end:
  52. let response = Echo_EchoResponse.with {
  53. $0.text = "Swift echo collect: " + parts.joined(separator: " ")
  54. }
  55. context.responsePromise.succeed(response)
  56. }
  57. })
  58. }
  59. public func update(
  60. context: StreamingResponseCallContext<Echo_EchoResponse>
  61. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  62. var count = 0
  63. return context.eventLoop.makeSucceededFuture({ event in
  64. switch event {
  65. case let .message(message):
  66. let response = Echo_EchoResponse.with {
  67. $0.text = "Swift echo update (\(count)): \(message.text)"
  68. }
  69. count += 1
  70. context.sendResponse(response, promise: nil)
  71. case .end:
  72. context.statusPromise.succeed(.ok)
  73. }
  74. })
  75. }
  76. }