rsnext/packages/next/server/api-utils/web.ts
Shu Ding a4a970bafa
Support necessary headers in the web server response (#36122)
This PR adds support of `Content-Length`, `Etag` and `X-Edge-Runtime` headers to the web server.

## Bug

- [ ] Related issues linked using `fixes #number`
- [x] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
2022-04-13 17:14:53 +00:00

28 lines
768 B
TypeScript

// Buffer.byteLength polyfill in the Edge runtime, with only utf8 strings
// supported at the moment.
export function byteLength(payload: string): number {
return new TextEncoder().encode(payload).buffer.byteLength
}
// Calculate the ETag for a payload.
export async function generateETag(payload: string) {
if (payload.length === 0) {
// fast-path empty
return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
}
// compute hash of entity
const hash = btoa(
String.fromCharCode.apply(
null,
new Uint8Array(
await crypto.subtle.digest('SHA-1', new TextEncoder().encode(payload))
) as any
)
).substring(0, 27)
// compute length of entity
const len = byteLength(payload)
return '"' + len.toString(16) + '-' + hash + '"'
}