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.21k stars 87 forks source link

Parsing ISO8601 date time from server fails due to milliseconds #537

Closed laurensvm closed 2 months ago

laurensvm commented 2 months ago

Question

The server returns date-time strings as 2023-12-28T11:08:38.303+01:00. The default JSONDecoder does not parse this properly and an extension is required to fallback to millisecond parsing. I'm wondering what in your opinion is the best way to solve this issue (preferably without changing the openapi spec, as many other services rely on it. I know it would be possible to parse it as a string and convert to Date manually, but this would require changing the openapi spec). Is it possible to provide a custom JSONDecoder to the generator with a DateFormatter able to handle the millisecond ISO8601 date-time?

Thanks a lot for this project and your help!

simonjbeaumont commented 2 months ago

@laurensvm Client.init accepts a configuration: OpenAPIRuntime.Configuration parameter. This allows you to specify a different (or custom) DateTranscoder.

By default, this is DateTranscoder.iso8601 which uses Foundation's default settings, which, as you point out, do not handle fractional seconds.

You can use .iso8601WithFractionalSeconds instead, which does handle this:

let client = Client(
    serverURL: URL(string: "http://localhost:8080/api")!,
    configuration: .init(dateTranscoder: .iso8601WithFractionalSeconds),  // <-- Specify the date transcoder here.
    transport: URLSessionTransport()
)
laurensvm commented 2 months ago

Thank you, this is exactly what I was looking for!