2
0

EchoAsyncProvider.swift 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2021, 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 GRPC
  18. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  19. public final class EchoAsyncProvider: Echo_EchoAsyncProvider {
  20. public let interceptors: Echo_EchoServerInterceptorFactoryProtocol?
  21. public init(interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil) {
  22. self.interceptors = interceptors
  23. }
  24. public func get(
  25. request: Echo_EchoRequest,
  26. context: GRPCAsyncServerCallContext
  27. ) async throws -> Echo_EchoResponse {
  28. return .with {
  29. $0.text = "Swift echo get: " + request.text
  30. }
  31. }
  32. public func expand(
  33. request: Echo_EchoRequest,
  34. responseStream: GRPCAsyncResponseStreamWriter<Echo_EchoResponse>,
  35. context: GRPCAsyncServerCallContext
  36. ) async throws {
  37. for (i, part) in request.text.components(separatedBy: " ").lazy.enumerated() {
  38. try await responseStream.send(.with { $0.text = "Swift echo expand (\(i)): \(part)" })
  39. }
  40. }
  41. public func collect(
  42. requestStream: GRPCAsyncRequestStream<Echo_EchoRequest>,
  43. context: GRPCAsyncServerCallContext
  44. ) async throws -> Echo_EchoResponse {
  45. let text = try await requestStream.reduce(into: "Swift echo collect:") { result, request in
  46. result += " \(request.text)"
  47. }
  48. return .with { $0.text = text }
  49. }
  50. public func update(
  51. requestStream: GRPCAsyncRequestStream<Echo_EchoRequest>,
  52. responseStream: GRPCAsyncResponseStreamWriter<Echo_EchoResponse>,
  53. context: GRPCAsyncServerCallContext
  54. ) async throws {
  55. var counter = 0
  56. for try await request in requestStream {
  57. let text = "Swift echo update (\(counter)): \(request.text)"
  58. try await responseStream.send(.with { $0.text = text })
  59. counter += 1
  60. }
  61. }
  62. }