|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftOpenAPIGenerator open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | +import OpenAPIRuntime |
| 15 | +import OpenAPIAsyncHTTPClient |
| 16 | +import Foundation |
| 17 | + |
| 18 | +@main struct BidirectionalEventStreamsClient { |
| 19 | + private static let templates: [String] = [ |
| 20 | + "Hello, %@!", "Good morning, %@!", "Hi, %@!", "Greetings, %@!", "Hey, %@!", "Hi there, %@!", |
| 21 | + "Good evening, %@!", |
| 22 | + ] |
| 23 | + static func main() async throws { |
| 24 | + let client = Client(serverURL: URL(string: "http://localhost:8080/api")!, transport: AsyncHTTPClientTransport()) |
| 25 | + do { |
| 26 | + print("Sending and fetching back greetings using JSON Lines") |
| 27 | + let (stream, continuation) = AsyncStream<Components.Schemas.Greeting>.makeStream() |
| 28 | + /// To keep it simple, using JSON Lines, as it most straightforward and easy way to have streams. |
| 29 | + /// For SSE and JSON Sequences cases please check `event-streams-client-example`. |
| 30 | + let requestBody: Operations.getGreetingsStream.Input.Body = .application_jsonl( |
| 31 | + .init(stream.asEncodedJSONLines(), length: .unknown, iterationBehavior: .single) |
| 32 | + ) |
| 33 | + let response = try await client.getGreetingsStream(query: .init(name: "Example"), body: requestBody) |
| 34 | + let greetingStream = try response.ok.body.application_jsonl.asDecodedJSONLines( |
| 35 | + of: Components.Schemas.Greeting.self |
| 36 | + ) |
| 37 | + try await withThrowingTaskGroup(of: Void.self) { group in |
| 38 | + // Listen for upcoming messages |
| 39 | + group.addTask { |
| 40 | + for try await greeting in greetingStream { |
| 41 | + try Task.checkCancellation() |
| 42 | + print("Got greeting: \(greeting.message)") |
| 43 | + } |
| 44 | + } |
| 45 | + // Send messages |
| 46 | + group.addTask { |
| 47 | + for template in Self.templates { |
| 48 | + try Task.checkCancellation() |
| 49 | + continuation.yield(.init(message: template)) |
| 50 | + try await Task.sleep(nanoseconds: 1 * 1_000_000_000) |
| 51 | + } |
| 52 | + continuation.finish() |
| 53 | + } |
| 54 | + return try await group.waitForAll() |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments