hey-api / openapi-ts

🚀 The OpenAPI to TypeScript codegen. Generate clients, SDKs, validators, and more. Support: @mrlubos
https://heyapi.dev
Other
1.39k stars 107 forks source link

Ensuring Reliable Data Returns with Axios’ throwOnError Setting #1142

Open Jannchie opened 1 month ago

Jannchie commented 1 month ago

Description

I’m currently using the Axios client and have configured it with the following settings:

client.setConfig({
  throwOnError: true,
})

Even though this setting automatically throws an error when one occurs, the type of the returned response can still be either an error or data. This implies that the data might be undefined.

The structure of the response is as follows:

const resp: (AxiosError<HTTPValidationError, any> & {
    data: undefined;
    error: HTTPValidationError;
}) | (AxiosResponse<unknown, any> & {
    ...;
})

I believe that if throwOnError is specified, then resp.data should be the return value defined by the API, and it shouldn’t be undefined. In the current situation, I still need to check whether resp.error is undefined in order to rule out the possibility of data being undefined.

Reproducible example or configuration

No response

OpenAPI specification (optional)

No response

System information (optional)

No response

amiryadid commented 3 days ago

It's not a solution, but the way I got around it was to set a default options object typed like this: const defaultOptions: Options & { throwOnError: true } This way I can still configure any option in the request but typescript treats throwOnError as always true, thus avoiding the need to check it every call.

Also relates to #961

mrlubos commented 3 days ago

@amiryadid where do you then pass defaultOptions? Could we make it so that you're able to extend the client interface to achieve the same effect? You'd be able to create a module override and declare the type however you want. Something like this https://stackoverflow.com/a/43955512