apple / swift-openapi-generator

Generate Swift client and server code from an OpenAPI document.
https://swiftpackageindex.com/apple/swift-openapi-generator/documentation
Apache License 2.0
1.45k stars 121 forks source link

Mapping to an AsyncSequence without exposing the generated internal types #615

Closed timbms closed 1 month ago

timbms commented 3 months ago

Question

I am using the excellent Server side events inside a framework that shall map to a model. How can I map to an AsyncSequence that does not expose the generated internal types?

czechboy0 commented 3 months ago

Hi @timbms,

are you saying you want an async sequence of opaque element types?

One way you could do that would be to write your own opaque wrapper type and map the sequence elements over to it.

public struct Wrapper {
    private let wrapped: MyGeneratedType
}

let opaqueSequence = decodedSequence.map { Wrapper(wrapped: $0) }
// use opaqueSequence
timbms commented 3 months ago

Hi @czechboy0,

I am trying to do this:

let decodedSequence = try await api.getSitemapEvents_1(path: path, query: query).ok.body.text_event_hyphen_stream.asDecodedServerSentEventsWithJSONData(of: Components.Schemas.SitemapWidgetEvent.self)
let opaqueSequence = decodedSequence.map { OpenHABSitemapWidgetEvent($0.data) }

However decodedSequence is of type: AsyncThrowingMapSequence<ServerSentEventsDeserializationSequence<ServerSentEventsLineDeserializationSequence<HTTPBody>>, ServerSentEventWithJSONData<Components.Schemas.SitemapWidgetEvent>>

and opaqueSequence of type>

AsyncMapSequence<AsyncThrowingMapSequence<ServerSentEventsDeserializationSequence<ServerSentEventsLineDeserializationSequence<HTTPBody>>, ServerSentEventWithJSONData<Components.Schemas.SitemapWidgetEvent>>, OpenHABSitemapWidgetEvent?>

Therefore it exposes Components.Schemas.SitemapWidgetEvent Not clear to me how I can make this opaque.

czechboy0 commented 3 months ago

What would you like the resulting async sequence type to be? What should its element type be?

timbms commented 3 months ago

I am fine with any Async....Sequence. It should just not refer to the internal type Components.Schemas.SitemapWidgetEvent but to the wrapper type OpenHABSitemapWidgetEvent.

czechboy0 commented 3 months ago

I see, if you're using Swift 6, then you could return this sequence from a method whose return type is some AsyncSequence<OpenHABSitemapWidgetEvent, Error>?

timbms commented 3 months ago

Thanks for the outlook on a possible solution: You are referring to SE-0421, aren't you. In the meantime I have manually specified the decodable class for the events I want to read from the stream.

czechboy0 commented 1 month ago

Closing as this is possible to do in Swift 6. In earlier Swift versions, we don't really have a way to do this without e.g. offering a separate API that vends a type-erased async sequence, which we'd like to avoid. It's also something that adopters can add on top without the generated code changing.