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

Response as a content "application/pdf" gets returned as response.text()

Open Bringordie opened this issue 3 years ago • 2 comments

Same issue as in https://github.com/ferdikoomen/openapi-typescript-codegen/issues/802

My goal is to get a "application/pdf" and serve it to my users something like:

const fileURL = URL.createObjectURL(data);
window.open(fileURL, '_blank');

I'm receiving "application/pdf" from our backend. I do not have enough knowledge of what my buddy is doing is the correct way. But he insists on sending it this way with this response header.

        "responses" : {
          "200" : {
            "description" : "Successful",
            "content" : {
              "application/pdf" : {
                "schema" : {
                  "type" : "string",
                  "format" : "binary"
                }
              }
            }
          },

Adding something like:

else if (contentType === 'application/pdf') {
    return await response.blob();
}

to getResponseBody would fix this issue:

async function getResponseBody(response: Response): Promise<any> {
    try {
        const contentType = response.headers.get('Content-Type');
        if (contentType) {
            const isJSON = contentType.toLowerCase().startsWith('application/json');
            if (isJSON) {
                return await response.json();
            } else if (contentType === 'application/pdf') {
                return await response.blob();
            } else {
                return await response.text();
            }
        }
    } catch (error) {
        console.error(error);
    }
    return null;
}

I've been unable to find another way to get this to work. Googeling I've tried to make a .text() (which is what I recieve) into a Blob, but that seems to not work either.

Bringordie avatar Mar 10 '22 12:03 Bringordie

And to add extra since it only has those 2 checks. Perhaps it should be expanded to handle the rest also if this is a valid issue ? https://developer.mozilla.org/en-US/docs/Web/API/Response#methods

Bringordie avatar Mar 10 '22 13:03 Bringordie

I have this issue as well, I don't think that adding a check for application/pdf is the right way to do it because you'll end up needing to add a near unlimited list of mime types, plus any mime type of text/* could be text or blob depending on how the data is being used.

I think the best way would be to check for the response type (binary) and handle accordingly. I've done that and created a PR: #986

loganbenjamin avatar Mar 19 '22 01:03 loganbenjamin