redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

OpenAPI codegen: Serializing dates (and anything else)

Open pgross41 opened this issue 3 years ago • 0 comments

I would like the date fields coming from the server to be stored as dates in redux. Better yet I'd like them to be types of our date library (dayjs). Redux doesn't love objects in its store but we've had no issues with it up until now. This could be implemented manually outside of schema generation but per https://github.com/reduxjs/redux-toolkit/issues/1441, enhanceEndpoints can't change the types. Would it be possible to automatically interpret strings in date-time format as Date? Query requests would convert from string to Date and mutator requests would convert back to string.

My preferred crazy idea though would be to add parseResponse and serializeRequest config options. Not sure if it's possible to do this while accommodating typescript but it would somehow map schema property types to a TS type. Strings are extra tricky because their type is a "string" but they have a format with them. This would allow us to customize any OpenAPI type however we wanted. Example:

const config: ConfigFile = {
    ...
    parseResponse: {
        'string:date-time': (value: string) => {
            return new Date(value);
        }
    },
    serializeRequest: {
        'string:date-time': (value: Date) => {
            return value.toISOString();
        }
    }
}

From the above, the code generator would infer the new type based on the return type of the custom callback.

Lastly in case someone has some insight, I was looking at the openapi-generator and it looks like someone implemented a redux-query client. Has there been any discussion around building out rtk-query? I may take a whack at that if the 2 ideas above are no good.

pgross41 avatar Jul 18 '22 17:07 pgross41