jeremydaly / lambda-api

Lightweight web framework for your serverless applications
https://serverless-api.com
MIT License
1.41k stars 125 forks source link

API returns invalid PDF #261

Closed thomasjetzinger closed 1 month ago

thomasjetzinger commented 4 months ago

Hi!

I have an endpoint which should allow the user to fetch a PDF, which is returned as bytearray, from an internal reporting server. This PDF should then be returned to the client:

`const pdfAsByteArray = await reportService.generateReportAndWait(user.user, reportParameters);

return this.response.header('Content-Type', 'application/pdf').sendFile(pdfAsByteArray);`

I've also add the media type "appication/pdf" to the "Binary meda types" section in the API Settings of my REST api. From my understanding the byte array should be converted to base64 and then automatically be converted back to binary in the client.

But the on client the response is still in base64 format!

What I'm doing wrong?

naorpeled commented 2 months ago

Hey @thomasjetzinger, sorry for the huge delay.

Is this still relevant?

thomasjetzinger commented 2 months ago

Hey @naorpeled

Yes, it's still relevant! Is this issue already know?

naorpeled commented 2 months ago

Hey @naorpeled

Yes, it's still relevant! Is this issue already know?

No, but I'll gladly look into this for you asap. (probably in few hours, when I get back home from work)

naorpeled commented 1 month ago

Hey @thomasjetzinger, sorry for the delay.

I've tried to reproduce the issue but had no luck. This code seems to work for me:

import createAPI from "lambda-api";

const api = createAPI({
  logger: true,
});

export const getAllItemsHandler = async (event, context) => {
  return await api.run(event, context);
};

api.get("/", async (req, res) => {
  const pdfByteArray = await getPdfByteArray();

  return res
    .header("Content-Type", "application/pdf")
    .sendFile(Buffer.from(pdfByteArray), {}, (err) => {
      if (err) {
        res.error("Custom File Error");
      }
    });
});

const getPdfByteArray = async () => {
  const pdf = await fetch(
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  );
  const pdfByteArray = await pdf.arrayBuffer();
  return pdfByteArray;
};
naorpeled commented 1 month ago

If you'd like we could hop on a call in the next few days and take a look together 🙏

naorpeled commented 1 month ago

Hey @thomasjetzinger, I'll be closing this issue as completed for now as I could not re-produce this issue.

Feel free to ping me here or over Twitter (X) if you need further assistance 🙏