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

Allow for custom types in path params serialization (and maybe other places serialization too)

Open JeanRemiDelteil opened this issue 1 year ago • 0 comments

Description

In an OpenAPI spec we have some type that are annotated with a specific format:

      properties:
        id:
          type: string
          format: uuid
          description: a unique identifier

You can also imagine having other format for the same JS primitive (emails, for example). We want to leverage this format to enforce some checks on the format, and build "safe value".

To do so:

  • In the generated TS types, the format: 'uuid' for type string is replaced by the Uuid type.
parameters: {
  path: {
    id: Uuid;
  };
};
  • The Uuid class extending String is used as constructor when deserializing.

The problem lies in the usage with the fetch api:

const petId: string = "0000-0000-0000";

api.GET('/api/pets/pet/{id}', {
  params: {
    path: {
      // TOFIX: Here the type of the 'id' key is incorrect, because if its type is "object" it will not be deserialized as a string, but as an object.
      // id: new Uuid(petId), // DOES NOT WORK even if Uuid extends String
      id: petId as unknown as Uuid, // Works, but it's a hack (string typed as Uuid)
    },
  },
})

Proposal

In the method defaultPathSerializer, the path parameters value's are tested in this order:

  • Array.isArray(value)
  • typeof value === "object"
  • default to string processing

If changed to the following it would allow custom string formats.

  • Array.isArray(value)
  • typeof value === "object" && !(value instanceof String)
  • default to string processing

Another possibility would be to allow passing a custom path serializer in the api builder, as the query and the body serializers.

Checklist

JeanRemiDelteil avatar May 13 '24 13:05 JeanRemiDelteil