I’m having trouble reading the request body in my worker. I’ve found a few options, but none seems to have the trifecta of being able to run in production, in the online simulator, and locally in Jest tests.
Option 1: body.json()
The request docs say that request.body
has a json()
method that returns a promise. And service-worker-mock supports body.json()
, which makes it easy to test workers locally. But it doesn’t work in the online editor. body.json
is undefined.
Option 2: getReader()
If I use request.body.getReader().read()
I can get the body, but it is consumed and can’t be read again. Specifically, I can’t pass that request on to the origin.
If I use request.body.tee()
, I get two readers – one that I can consume in my worker and one that I can pass on to the origin. This too consumes the original request.body
. My first attempt was this:
const [ body1, body2 ] = request.body.tee();
request.body = body1;
const { value: bodyIntArray } = await body2.getReader().read()
const bodyJSON = new TextDecoder().decode(bodyIntArray)
return JSON.parse(bodyJSON)
Unfortunately, the request
is immutable, so request.body = body1
throws an exception. Nor does this workaround seem to work:
request = new Request(request, { body: body1 })
Any suggestions?