#Properly parsing JSON body using Bun Serve Fetch Method

1 messages · Page 1 of 1 (latest)

chrome pike
#

Hello, is there a proper way to handle the JSON body of a Bun Request ?
I could not find anything more wise and I am not really satisfied about it, Try / Catch seem like a "Mehh idc" kind of method

    let reqBody: JSON | null;
    let reqRawBody: string | null;
    try {
      reqRawBody = await req.text();
      reqBody = JSON.parse(reqRawBody);
    } catch {};
mint prawn
#

Here's what I use

const json = await req.json().catch(() => null);
if (json === null) {
  // Return 400 or whatever
}
// Then do some validations and continue
chrome pike
#

Im sad it still requires await because for me it looks really not that necessary

#

but thank you im goin to go with that

mint prawn
#

If you have written raw node http before you will know this process

#

but ofc node is slower because you have to do that in pure js

chrome pike
#

Everything network related besides http, i don't really know much

#

But yeah I guess there is a reason why every wrapper uses it

mint prawn
#

Haven't written this stuff for a long time so these are only things that I remember

chrome pike
#

yeah I remember thoses (hated em)

mint prawn
#

and it is faster

chrome pike
#

are you talking about fetch api ? maybe faster but they still requires away as far as I know

mint prawn
#

await req.json() looks like a syntactic sugar to JSON.parse(await req.text())
But it is faster because you handle everything in native code

chrome pike
#

yes ofc and its just to make it easier for devs too

mint prawn
#

like Request Response creation is slow

#

and also that AbortSIgnal in Request

#

I'm glad bun chose a good lib for HTTP

chrome pike
#

I like some of it but hate some others

#

I always have to make wrappers around the original req res personally

mint prawn
#

I also do that

#

create a context object that wraps

#

because attaching more props is faster than directly attaching to the request object

#

Here's mine you can take a look

chrome pike
#

Imm going to take a look

chrome pike
#

@mint prawn Hey sorry for not coming back, just wanted to say thank you your method worked like a charm and is just nicer to read