0

Currently, I have a route handler that returns a stream of a PDF as the response body:

api.get('/create/pdf', async ({ request, response }) => {
  const { pdfStream } = await createPdfStream() // This returns a Transform stream
  response.body = pdfStream 
})

I am able to get this PDF on the client by doing the following:

const response = await fetch('/create/pdf')
const blob = await response.blob()
const pdfUrl = URL.createObjectUrl(blob) // I can now use `pdfUrl` to render the PDF

However, I now want to return some additional properties from the API route and so I want to make it a JSON response instead of just returning the stream. Is this possible? I basically want to change my route handler to something like this:

api.get('/create/pdf', async ({ request, response }) => {
  const { pdfStream, pdfMetadata } = await createPdfStream() // This returns a Transform stream
  response.body = {
    pdfStream,
    pdfMetadata
  }
})

But if I did this, I am not sure how I would be able to access the PDF on the client anymore as I won't be able to do response.blob() anymore, I could only do response.json(). Does anyone have any tips?

inhwrbp
  • 569
  • 2
  • 4
  • 17
  • Not possible. JSON is a static data structure, it has no idea what to do with a stream. – Eric Guan Jun 28 '20 at 23:16
  • Does this answer your question? [Koa2 - How to write to response stream?](https://stackoverflow.com/questions/51571054/koa2-how-to-write-to-response-stream) – explorer Jun 28 '20 at 23:20
  • @EricGuan I see, thanks. Is there a way to convert a stream into something I can send in the JSON and then convert it back or use it somehow on the client? – inhwrbp Jun 28 '20 at 23:24
  • @inhwrbp i would look into transforming the PDF into a base64 string. Since it's a string, it can be in the JSON payload, along with your metadata. Then, on the client, there should be a way to convert the base64 back into a viewable PDF. – Eric Guan Jun 29 '20 at 00:48

0 Answers0