Custom type and deserialization into this type
Is there a way to use a custom types in the schema file? And deserialize from string into this type at runtime?
I have the OpenAPI spec like this (just a snippet):
{
"components": {
"schemas": {
"SomeModel": {
"type": "object",
"properties": {
"someProperty": {
"type": "string",
"format": "MyCustomType"
}
}
}
}
}
}
Which will generate this into the schema file:
export type SomeModel = {
/**
* @format MyCustomType
*/
someProperty: string;
}
But I want to have it like this:
import {MyCustomType} from 'some-library';
export type SomeModel = {
someProperty: MyCustomType;
}
And deserializing the fetched response during runtime into the MyCustomType
I have managed the first part, so my schema file hast the correct custom type and also the import. I have managed this via a custom context.writeFile function which inject the import and manipulating the openAPIDocument in the context to adjust the type.
Now the only thing which is missing is the deserializing and serializing in the fetcher. Deserializing from string to MyCustomType and serializing from MyCustomType to string. Any advice for this?
@hsimpson did you manage to solve this? do you have example? π
@andriijas unfortunately not.
Yeah as you say itβs one thing to generate the custom type but in the other end you need to parse each response and deep check / parse attributes with the custom type. It sounds easy on paper but more complicated in reality
Yeah, this is not an easy problem, the trick will be to generate some runtime parser from the specs (since this is where you have the information). I did this a long time ago on another project, with zod schema. To try to describe the flow, we have:
- specs -> runtime parser (a function that takes
operationIdthepayloadand return the wanted formattedresponse) - in the fetcher, you can use this function
Of course the game, is to have typescript following during all the pipeline π