orval
orval copied to clipboard
Axios: generator does not seem to support multiple response types #1588
Description
If you use an openAPI schema with multiple responses like this:
"/api/user": {
"get": {
"operationId": "get_user",
"summary": "Get User",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/UserResponse" }
}
}
},
"400": {
"description": "Bad Request",
"content": {
"application/json": {
"schema": { "$ref": "#/components/schemas/ApiErrorResponse" }
}
}
}
The generated fetch will only have the 200 response type (in this example UserResponse). It does not seem to generate a union type for the method return type.
Expected Solution
There was a similar issue with fetch that was solved
Current Workaround
I provide my own response type, but I manually typed it (instead of using openapi spec)
export const customClient = <T>(
config: AxiosRequestConfig,
maybeOptions?: AxiosRequestConfig,
): Promise<ReponseType<T>> => {
// ... implementation
}
type ReponseType<TRes> = AxiosResponse<
| TRes
| {
status: 400;
statusText: string;
data: {
message: {
name: string;
message: string;
statusCode: 400;
errorLevel: string;
context: object;
};
};
}
>;
@ajubin isn't that documented here: https://orval.dev/guides/custom-axios
so in my demo app all of my 4xx and 5xx errors return an HttpProblem response which I map with 1 line of Axios here: https://github.com/melloware/quarkus-primereact/blob/e6c2317a77deb969a6f41967072c6f5a7da80d38/src/main/webui/src/service/AxiosMutator.ts#L26
my HttpProblem was generated by Orval: https://github.com/melloware/quarkus-primereact/blob/e6c2317a77deb969a6f41967072c6f5a7da80d38/src/main/webui/src/service/CarService.ts#L80-L95
well for now I have something similar than you, but it's still a limitation compared to the fetch client. Indeed, we have a type that is not route specific
Let me take another example, I have a route POST /car that create a car and have the following response:
- 201: created
- 412 (precondition not met, specific to this route): containing a body explaining what is missing
For other routes, I never have 412.
I'd love to have something like that generated
// generated-client.ts
type PostCarResponse = CarCreatedResponse | Car412Response
Interesting. Yeah I wasn't sure if this was some limitation but it looks like Orval has always done this for Axios and the Fetch client was written more recently. @anymaniax will know the history of it?