Stripe writable stream + nestjs [TypeError: Converting circular structure to JSON]

262 views Asked by At

Im integrating stripes invoicing and quotes into my nestjs api. I am trying to download the quote PDF option but I having issues with node createWriteStream.

Stripe API says to implement the code as follows

const {createWriteStream} = require("fs");

// Returns a stream.Readable
const pdf = await stripe.quotes
  .pdf("qt_0J1EnX589O8KAxCGEdmhZY3r");

await new Promise((resolve) => {
  pdf.pipe(createWriteStream("/tmp/tmp.pdf"));
  pdf.on("end", () => resolve());
})

My Code

@Get('/:id/pdf')
async downloadQuote(@Param('id') id: string) {
    const pdf = await this._stripeClient.quotes.pdf(id)

    await new Promise<void>((resolve) => {
        pdf.pipe(createWriteStream('/tmp/tmp.pdf'))
        pdf.on('end', () => resolve())
    })


    return {
        success: true,
        data: pdf
    }
}

Error

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'IncomingMessage'
    |     property 'req' -> object with constructor 'ClientRequest'
    --- property 'res' closes the circle
1

There are 1 answers

0
os4m37 On

You are trying to convert the pdf to Json.

Your endpoint should be like this instead:

@Get('/:id/pdf')
async downloadQuote(@Param('id') id: string, @Res() res: Response) {
  const pdf = await this._stripeClient.quotes.pdf(id);
  pdf.pipe(res);
}

You can refer to this NestJs guide about streaming files.