gauntface/simple-push-demo

Switch to sending ArrayBuffer to proxy server

gauntface opened this issue · 1 comments

From @FluorescentHallucinogen:

By dropping Base64 conversion I mean sending fetch() request to CORS proxy "as is" with body of type ArrayBuffer and pass the original push endpoint address in the request header, e.g. X-Endpoint. That's exactly what @beverloo did in his demo https://tests.peter.sh/push-message-generator/. In this case, there is no need to JSON.stringify and convert the body to Base64. See https://github.com/beverloo/peter.sh/blob/aa735a65e42e3d86db3d12adf72dcea666a212f6/tests/push-message-generator/push_generator.js#L779-L791.

#205 (comment)

I feel like this wasn't an option a years and years ago, so would be worth checking out. The express server may need the express.raw() or some other middleware.

I did a slightly different method, i used FormData and posted the endpoint and headers as plain text and for the body i used Blob.

// server
'/sendpush' (req, res) {
    new Response(req, { headers: req.headers }).formData().then(fd => {
      // End the request early, we don't need to wait for the push service.
      // And we don't need to send any data back to the browser.
      res.writeHead(204, 'No Content', {})

      // `request` kind of resembles native whatwg Request (apart from headers)
      const request = Object.fromEntries(fd)

      fetch(request.url, {
        method: request.method,
        headers: {
          ...JSON.parse(request.headers),
          Urgency: 'high',
        },
        body: request.body
      }).then(res => {
        // console.log('ok', res.ok)
        // console.log('status', res.status)
        // console.log('statusText', res.statusText)
        // console.log('headers', res.headers)
        res.text()
        .then(console.log)
      })
    })
  }
// client
const req = await encryptionHelper.getRequestDetails
const fd = new FormData()
    fd.set('body', new Blob([req.body || '']))
    fd.set('headers', JSON.stringify(req.headers))
    fd.set('method', req.method)
    fd.set('url', req.url)

    fetch('/sendpush', { method: 'POST', body: fd })