openapi-codegen icon indicating copy to clipboard operation
openapi-codegen copied to clipboard

Custom type and deserialization into this type

Open hsimpson opened this issue 3 years ago β€’ 5 comments

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

hsimpson avatar Nov 18 '22 01:11 hsimpson

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 avatar Dec 24 '22 12:12 hsimpson

@hsimpson did you manage to solve this? do you have example? πŸ™

andriijas avatar Feb 01 '23 12:02 andriijas

@andriijas unfortunately not.

hsimpson avatar Feb 01 '23 17:02 hsimpson

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

andriijas avatar Feb 01 '23 18:02 andriijas

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 operationId the payload and return the wanted formatted response)
  • in the fetcher, you can use this function

Of course the game, is to have typescript following during all the pipeline πŸ˜…

fabien0102 avatar Apr 04 '23 07:04 fabien0102