Skip to content

Commit

Permalink
feat: addsendNoContent utility to create a 204 response (#250)
Browse files Browse the repository at this point in the history
* feat: add sendEmpty helper method to create a response with an empty payload

* fix linter

* small updates

* update readme

Co-authored-by: Pooya Parsa <[email protected]>
  • Loading branch information
tobiasdiez and pi0 authored Dec 15, 2022
1 parent 4e52381 commit 0979cac
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ H3 has concept of compasable utilities that accept `event` (from `eventHandler((
- `createError({ statusCode, statusMessage, data? })`
- `sendProxy(event, { target, headers?, fetchOptions?, fetch?, sendStream? })`
- `proxyRequest(event, { target, headers?, fetchOptions?, fetch?, sendStream? })`
- `sendNoContent(event, code = 204)`
- `setResponseStatus(event, status)`
- `getResponseStatus(event)`
- `getResponseStatusText(event)`
Expand Down
16 changes: 16 additions & 0 deletions src/utils/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@ export function send(event: H3Event, data?: any, type?: string): Promise<void> {
});
}

/**
* Respond with an empty payload.<br>
* Note that calling this function will close the connection and no other data can be sent to the client afterwards.
*
* @param event H3 event
* @param code status code to be send. By default, it is `204 No Content`.
*/
export function sendNoContent(event: H3Event, code = 204) {
event.node.res.statusCode = code;
// 204 responses MUST NOT have a Content-Length header field (https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2)
if (event.node.res.statusCode === 204) {
event.node.res.removeHeader("content-length");
}
event.node.res.end();
}

export function setResponseStatus(
event: H3Event,
code: number,
Expand Down

0 comments on commit 0979cac

Please sign in to comment.