asteasolutions / zod-to-openapi

A library that generates OpenAPI (Swagger) docs from Zod schemas
MIT License
914 stars 57 forks source link

default response doesn't accept a valid SchemaObject in 5.2.0 #155

Closed callmeberzerker closed 1 year ago

callmeberzerker commented 1 year ago

So for some reason in 5.x.x version of the lib, the default response doesn't accept the valid zod type which is ErrorDto.

Type 'ZodObject<{ code: ...>' is not assignable to type 'SchemaObject | ReferenceObject | undefined'.ts(2322)
openapi31.d.ts(130, 5): The expected type comes from property 'schema' which is declared here on type 'MediaTypeObject'

Now that I notice some details I am using v3 openAPIRegistry and OpenApiGeneratorV3 -> not sure why its using openapid31.d.ts above

Repro below 👇

export const registry = new OpenAPIRegistry();

export const GetUserDto = registry.register(
    'GetUserDto',
    z
        .object({
            username: z.string().nullable(),
        })
        .strict(),
);

const ErrorDto = registry.register('ErrorDto', z
        .object({
            code: z.string().nullable(),
        })
        .strict());

export const GetUser: RouteConfig = {
    method: 'get',
    path: '/user',
    summary: 'Returns general information about the currently signed-in user.',
    responses: {
        200: {
            description: 'Object with user data.',
            content: {
                'application/json': {
                    schema: GetUserDto,
                },
            },
        },
        default: {
            description: 'Default error responses',
            content: {
                'application/json': {
                    schema: ErrorDto,
                },
            },
        },
    },
};
callmeberzerker commented 1 year ago

This is a TS error only, I can verify that the generateComponents call works and it is producing a valid open api yml 💯

AGalabov commented 1 year ago

@callmeberzerker thank you for reporting that. And yes as you've noticed this is only a TS error and it is an easy one to fix. I've just opened up a PR

AGalabov commented 1 year ago

Should now be fixed in v5.3.0