Skip to content

Some fetch similarities #4536

Open
Open
@jimmywarting

Description

@jimmywarting

I was wondering if we could have a few of the methods that exist on the window.Request.prototype since we are all mostly familiar with working with fetch on frontend and backend (using node-fetch/undici). And maybe have it work a little bit like a service worker.

namely

  • Request.prototype.arrayBuffer
  • Request.prototype.text
  • Request.prototype.formData
  • Request.prototype.blob
  • Request.prototype.json

All of this returns a promise with the hole body being parsed. so you don't have to work with streams

So instead of having to do this blocking request (that don't call the next handler until it's finish

// manual body parser
app.post(path, function (req, res, next) {
  const chunks = []
  req.on('data', data => chunks.push(data))
  req.on('end', () => {
    const body = Buffer.concat(chunks)
    // do something with the hole body
    req.body = JSON.parse(body.toString())
    next()
  })
}, routeHandler)
// or
app.use(bodyParser.json(), routeHandler)

we could just do what is normally done in service worker & the fetch api:

app.post(path, async function routeHandler (req, res) {
  const arrayBuffer = await req.arrayBuffer()
  const text = await req.text()
  const blob = await req.blob()
  const json = await req.json()
  const formData = await req.formData()
})

The benefit of this would be that your route handler would be able to retrieve request headers first. So you can validate more quickly if a user is authenticated, if the payload is too large by looking at the content-length, what kind of content-type they are sending etc

ofc it is also possible to do that already but it would would require 3
handlers and look something like: app.post(authenticate, bodyParser.json(), handler)

I don't know so much about formData since it requires some more work/parsing and it would require some formdata package

Node 15.8 introduced buffer.Blob so we also have that.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions