Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fastify Swagger not managing enumerators as expected

We are working on a backend with Fastify, declaring schemas with Typebox and generating OpenApi definitions with Fastify Swagger
We are facing some problems with enums or similar during docs generation

Let’s say we declare a typebox enumerator in one of the following ways

export const ProviderType = Type.Union([
  Type.Literal("sms"),
  Type.Literal("email"),
]);

//OR

enum Providers {
  SMS = "sms",
  EMAIL = "email",
}

export const ProviderType = Type.Enum(Providers);

When the open api docs are generated we get this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

- schema:
    anyOf:
        - type: string
          enum:
              - sms
        - type: string
          enum:
              - email

That is not what we expect, but something like

schema:
    type: string
    enum: [sms, email]

Otherwise, the places where the enum is used are not correctly rendered by the various packages.

Did you already face this problem?

>Solution :

The TypeBox project does not support enum ATM as said by the lead maintainer.

It suggests a workaround:

const StringEnum = <T extends string[]>(items: [...T]) =>
  Type.Unsafe<T[number]>({ type: "string", enum: items });

export const ProviderType = StringEnum(["email", "sms"]);

// BECOMES
 - schema:
            type: string
            enum:
              - email
              - sms

So the fastify-swagger would be using the enum keyword.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading