swagger-typescript-api
swagger-typescript-api copied to clipboard
Mapping schema iso Dates to js Date
Context
I understand I can use this
primitiveTypeConstructs: (struct) => ({
string: {
date: 'Date',
},
})
To make sure Schema date is mapped to js Date. But this will just change TS type in the api response interfaces,
interface ResponseType {
someDate: string; // becomes Date
}
It will not actually make the generated api transform those date strings into a data like const mappedDate = new Date(isoString)
My Question
Is there a way to make sure the actual api created already maps the dates it finds in the response to js Date.
I can think of one way of doing this which would be to write my own axios interceptor to do this. Something like this https://weblog.west-wind.com/posts/2014/jan/06/javascript-json-date-parsing-and-real-dates and then the interceptor could do
var date = JSON.parse(JSON.stringify(data),JSON.dateParser);
I am thinking about his coming from GraphQL where I can use an Apollo client transformer to auto cast all iso strings to dates.
Please let me know if there is another/better way to do this.
Thanks
Just as a note: openapi-generator does this and it is a nightmare to work with. It's the exact reason why I'm looking for an alternative. JS dates lack timezone support and the API is generally very clunky.
I was thinking about an alternative to make the date parsing really flexible but it would only work for the programmatic configuration. A combination of two callbacks could be used:
function parseDate<T>(_: string): T;
function stringifyDate<T>(_: T) => string;
The type for date on interfaces could then be inferred by:
interface Order {
// ...
createdOn: ReturnType<typeof parseDate>,
}
This way we could fully exchanged the used date library (I would recommend luxon btw.)