kwhitley / itty-router

A little router.
MIT License
1.7k stars 77 forks source link

undocumented how to change status code of json response #175

Closed susickypavel closed 1 year ago

susickypavel commented 1 year ago

Describe the Issue

There is no documentation regarding how to change the status code of the response with json helper function (e.g. 201).

Example Router Code

router.post("/", (request) => {
    return json("?")
});

Expected Behavior

A clear and concise way how to change the status code.

Environment (please complete the following information):

Additional Context

There is a way to change the status code with second argument in json function but the type describing the parameter is absolutely unhelpful object returned by the createResponse function. Similarly status method only accepts 1 argument which is the status code, this is also a downgrade from v3 where I could pass a second argument with value of the response body.

kwhitley commented 1 year ago

Hey @susickypavel!

First of all, you're definitely right - the documentation could be clearer. Currently, with any of the helpers emitted from createResponse (e.g. json), the first param is the payload, the second is an optional ResponseInit argument (just like a native call to new Response(). The only difference is that it separates out the headers first to stitch in the appropriate MIME type.

This means you can always do the following to force a status code:

json({ foo: 'bar' }, { status: 202 })

// translates directly to:
new Response('{"foo":"bar"}', {
  status: 202,
  headers: {
    'content-type': 'application/json',
  }
})

It also means you can add in headers and such the same way as with the native Response:

json({ foo: 'bar' }, {
  headers: {
    'x-custom': 'my custom header',
  }
})

Definitely need to clarify this in the docs though!


I'm deciding what to do about the status bit... I was even tempted to drop it entirely from the v4 spec (there are a couple items I dropped from itty-router-extras during this migration), as the previous signature was very arbitrary (casting into a "message" attribute) - so I wasn't sure how much it was used outside of a blank status response (which I included).

susickypavel commented 1 year ago

The major problem was that the second optional argument wasn't typed as ResponseInit, which you've fixed. If you add the example bit above to the docs, I think it's more than enough.

Regarding the status function, I think it's okay for newcomers, but I was quite surprised to see that its API has changed during migration to v4.

kwhitley commented 1 year ago

Should be live in 4.0.13 - thanks!