|
| 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 OpenAPIURLSession |
| 16 | +import Foundation |
| 17 | + |
| 18 | +@main struct EventStreamsClient { |
| 19 | + static func main() async throws { |
| 20 | + let client = Client(serverURL: URL(string: "http://localhost:8080/api")!, transport: URLSessionTransport()) |
| 21 | + do { |
| 22 | + print("Fetching greetings using JSON Lines") |
| 23 | + let response = try await client.getGreetingsStream( |
| 24 | + query: .init(name: "Example", count: 3), |
| 25 | + headers: .init(accept: [.init(contentType: .application_jsonl)]) |
| 26 | + ) |
| 27 | + let greetingStream = try response.ok.body.application_jsonl.asDecodedJSONLines( |
| 28 | + of: Components.Schemas.Greeting.self |
| 29 | + ) |
| 30 | + for try await greeting in greetingStream { print("Got greeting: \(greeting.message)") } |
| 31 | + } |
| 32 | + do { |
| 33 | + print("Fetching greetings using JSON Sequence") |
| 34 | + let response = try await client.getGreetingsStream( |
| 35 | + query: .init(name: "Example", count: 3), |
| 36 | + headers: .init(accept: [.init(contentType: .application_json_hyphen_seq)]) |
| 37 | + ) |
| 38 | + let greetingStream = try response.ok.body.application_json_hyphen_seq.asDecodedJSONSequence( |
| 39 | + of: Components.Schemas.Greeting.self |
| 40 | + ) |
| 41 | + for try await greeting in greetingStream { print("Got greeting: \(greeting.message)") } |
| 42 | + } |
| 43 | + do { |
| 44 | + print("Fetching greetings using Server-sent Events") |
| 45 | + let response = try await client.getGreetingsStream( |
| 46 | + query: .init(name: "Example", count: 3), |
| 47 | + headers: .init(accept: [.init(contentType: .text_event_hyphen_stream)]) |
| 48 | + ) |
| 49 | + let greetingStream = try response.ok.body.text_event_hyphen_stream.asDecodedServerSentEventsWithJSONData( |
| 50 | + of: Components.Schemas.Greeting.self |
| 51 | + ) |
| 52 | + for try await greeting in greetingStream { print("Got greeting: \(greeting.data?.message ?? "<nil>")") } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments