Description
Suggestion:
Would it be desirable to have another option unwrapResponseDataWithErrors
or perhaps to turn unwrapResponseData
into a union 'disabled' | 'responseOnly' | 'responseAndError'
?
At the moment, it seems that unwrapResponseData
is not including the error and default response types.
Here:
swagger-typescript-api/templates/base/http-clients/fetch-http-client.ejs
Lines 170 to 175 in 0e251bb
This could be something like this instead:
<% if (config.unwrapResponseData) { %>
}: FullRequestParams): Promise<T> => {
<% } else if (config.unwrapResponseDataWithErrors) { %>
}: FullRequestParams): Promise<T | E> => {
<% } else { %>
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
<% } %>
Maybe I am misunderstanding the intent behind unwrapResponseData
and this is not a good idea for reasons. But if this is something that could be useful, I am happy to contribute with a PR.
Context
I have the following (shortened) OpenAPI spec:
The takeaway from this specification is that I expect the return type to be something like this:
export type ApiResponse =
| {
success: 'true';
data: object;
}
| {
success: 'false';
error:
| 'bad-request'
| 'github-api-error'
| 'parse-or-unknown'
| 'missing-envs'
| 'blob-storage-error'
| 'file-too-large';
description: string;
};
I generate a client from the specification above using swagger-typescript-api
version 13.1.3
:
import { generateApi } from 'swagger-typescript-api';
import specification from '...';
(async () => {
await generateApi({ spec: specification, output: process.cwd(), unwrapResponseData: true });
})();
The problem
The client works, but unwrapResponseData
only includes the response type for status 200
, so the return type that I'm actually getting is this:
export type ApiResponse = {
success: 'true';
data: object;
};
The solution
If I want the return type to include the error; in the generated client, all I need to do is modify this line:
To be
public request = async <T = any, E = any>({
body,
secure,
path,
type,
query,
format,
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<T | E> => { // Added | E here
Instead of
public request = async <T = any, E = any>({
body,
secure,
path,
type,
query,
format,
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<T> => {