Skip to content

204 response causes wrong data to be undefined #1933

Closed
@DjordyKoert

Description

@DjordyKoert

Description

Having a 204 response in combination with a 200 response in the generated type causes the returned data to become undefined

image

Generated openapi.ts file by openapi-typescript:

export interface operations {
    get_getOrdersByCustomerId: {
        parameters: {
            query?: {
                /** @description Limit the amount of orders returned */
                limit?: number;
                /** @description Offset results */
                offset?: number;
            };
            header?: never;
            path: {
                customerId: string;
            };
            cookie?: never;
        };
        requestBody?: never;
        responses: {
            /** @description Returns all orders for a customer */
            200: {
                headers: {
                    [name: string]: unknown;
                };
                content: {
                    "application/json": components["schemas"]["OrderDTO"][];
                };
            };
            /** @description No orders found for customer */
            204: {
                headers: {
                    [name: string]: unknown;
                };
                content?: never;
            };
        };
    };
}

Reproduction

Have an operation as defined above (with a 200 and a 204 with no content). Then attempt to use the openapi-fetch client for the operation.

Expected result

I expected the type a union of components["schemas"]["OrderDTO"][] | undefined and for me to not have to do a manual type assertion.

export type UseOpenApiFetchHookOptions<
    T extends keyof paths,
    TMethod extends keyof paths[T],
    TOperation extends paths[T][TMethod] = paths[T][TMethod],
> = ParamsOption<TOperation> & RequestBodyOption<TOperation> & {
    // add your custom options here
    reactQuery?: {
        enabled: boolean; // Note: React Query type’s inference is difficult to apply automatically, hence manual option passing here
        // add other React Query options as needed
    };
};

const getCustomerOrders: keyof paths = '/api/v1/customers/{customerId}/orders';
export const customerOrdersOptions = ({ params }: UseOpenApiFetchHookOptions<typeof getCustomerOrders, 'get'>) => queryOptions({
    placeholderData: keepPreviousData,
    queryFn: async ({ signal }) => {
        const { data, response } = await client.GET('/api/v1/customers/{customerId}/orders', {
            params,
            parseAs: 'json',
            signal,
        });

        if (!response.ok) {
            throw 'error';
        }

        if (response.status === 204) { // Unrelated, Fix for 204's returning an empty object {}
            return null;
        }

        return data as unknown as Array<components['schemas']['OrderDTO']>; // Assertion should not be needed here
    },
    queryKey: [
        getCustomerOrders,
        params,
    ],
});

Checklist

Metadata

Metadata

Assignees

No one assigned

    Labels

    PRs welcomePRs are welcome to solve this issue!bugSomething isn't workinggood first issueStraightforward problem, solvable for first-time contributors without deep knowledge of the projectopenapi-fetchRelevant to the openapi-fetch library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions