samedi 11 mars 2017

How to PUT a PDF with chai-http

Alright this is a pretty wholistic question here, as I need to know both about process and best-practices. Critiques be welcome!

I'm writing a test for a PDF-to-image API endpoint. As such, I need to PUT the PDF to the endpoint. The endpoint will save it locally, convert it, store the sequence of images in an S3 bucket, and then send back an array of URLs. But, since I'm writing this test largely to assist in development, none of that happens yet. I just want to make sure I can receive the PDF at the endpoint, and save it. Check out the test code below:

// testing dependencies
const chai = require("chai")
const chaiHttp = require("chai-http")
const should = chai.should()
const server = require('./../index.js')

chai.use(chaiHttp)

// utility dependencies
const fs = require('fs')

describe("PDF upload", () => {
  it("should PUT my pdf", (done) => {
    fs.readFile('./content/pdf/lockheed.pdf', (err, res) => {
      if (err) { console.error(err) }
      else {
        chai.request(server)
          .put('/v1/convert-pdf')
          .set('Content-Type', 'application/pdf')
          .send({ pdf: res })
          .end((err, res) => {
            console.log("got the res")
            if (err) { console.error(err) }
            else { console.log(res.body) }

            done()
          })
      }
    })
  })
})

Before I set the Content-Type header, I would simply get a 413 from the server (request too large). I've set all my timeouts and max request size really big so this really shouldn't be an issue. But now that I have application/pdf in the header, I get this error:

Uncaught TypeError: "string" must be a string, Buffer, or ArrayBuffer

This was much more helpful, and led me to this SO which pipes the file to a request. However, I'm really not sure how to accomplish this via chai-http so that my server can successfully get and save the pdf to a local file.

Aucun commentaire:

Enregistrer un commentaire