openapi-typescript-codegen icon indicating copy to clipboard operation
openapi-typescript-codegen copied to clipboard

Support for binary response

Open jacobator opened this issue 2 years ago • 1 comments

Hey there,

Is there any chance you could add support for binary response types (images)? I saw that this was already requested 2 years ago https://github.com/ferdikoomen/openapi-typescript-codegen/issues/802

Here's a partial openAPI definition:

paths:
  /images/{imagePath}:
    get:
      responses:
        '200':
          description: OK
          content:
            image/png:
              schema:
                type: string
                format: binary

Basically it's just a url to an image file that returns an image (e.g.: imgages/hello.png).

Here's a potential solution for this:

src/templates/core/fetch/getResponseBody.hbs

export const getResponseBody = async (response: Response): Promise<any> => {
  if (response.status !== 204) {
    try {
      const contentType = response.headers.get('Content-Type');
      if (contentType) {
        const jsonTypes = ['application/json', 'application/problem+json'];
        const isJSON = jsonTypes.some(type =>
          contentType.toLowerCase().startsWith(type),
        );
        const isBinary = contentType.toLowerCase().startsWith('image/');
        if (isJSON) {
          return await response.json();
        } else if (isBinary) {
          return await response.blob();
        } else {
          return await response.text();
        }
      }
    } catch (error) {
      console.error(error);
    }
  }
  return undefined;
};

jacobator avatar May 24 '23 14:05 jacobator

Can you verify if this is still the case? I just tried it and after adding the

 schema:
                type: string
                format: binary

to my OpenAPI spec I get a beautiful Blob endpoint generated

public viewImage(
        id: number,
    ): Observable<Blob> {
        return __request(OpenAPI, this.http, {
            method: 'GET',
            url: '/iamges/{id}/image',
            path: {
                'id': id,
            },
            errors: {
                404: `Not found`,
                422: `Validation Error`,
            },
        });
    }

ScholliYT avatar Nov 21 '23 11:11 ScholliYT