EchoService.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. struct EchoService: Echo_Echo.SimpleServiceProtocol {
  18. func get(
  19. request: Echo_EchoRequest,
  20. context: ServerContext
  21. ) async throws -> Echo_EchoResponse {
  22. return .with { $0.text = request.text }
  23. }
  24. func collect(
  25. request: RPCAsyncSequence<Echo_EchoRequest, any Error>,
  26. context: ServerContext
  27. ) async throws -> Echo_EchoResponse {
  28. let messages = try await request.reduce(into: []) { $0.append($1.text) }
  29. let joined = messages.joined(separator: " ")
  30. return .with { $0.text = joined }
  31. }
  32. func expand(
  33. request: Echo_EchoRequest,
  34. response: RPCWriter<Echo_EchoResponse>,
  35. context: ServerContext
  36. ) async throws {
  37. let parts = request.text.split(separator: " ")
  38. let messages = parts.map { part in Echo_EchoResponse.with { $0.text = String(part) } }
  39. try await response.write(contentsOf: messages)
  40. }
  41. func update(
  42. request: RPCAsyncSequence<Echo_EchoRequest, any Error>,
  43. response: RPCWriter<Echo_EchoResponse>,
  44. context: ServerContext
  45. ) async throws {
  46. for try await message in request {
  47. try await response.write(.with { $0.text = message.text })
  48. }
  49. }
  50. }