Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(writeEarlyHints): handle object-format early hints #202

Merged
merged 7 commits into from
Oct 17, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 10 additions & 14 deletions src/utils/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,35 +86,31 @@ export function sendStream (event: H3Event, data: any): Promise<void> {
})
}

export function writeEarlyHints (event: H3Event, hints: Record<string, string | string[]>, callback?: () => void) {
const noop = () => {}
export function writeEarlyHints (event: H3Event, hints: string | string[] | Record<string, string | string[]>, cb: () => void = noop) {
if (!event.res.socket && !('writeEarlyHints' in event.res)) {
if (callback) {
callback()
}
cb()
return
}

// Normalize if string is provided
if (typeof hints === 'string') {
// Normalize if string or string[] is provided
if (typeof hints === 'string' || Array.isArray(hints)) {
hints = { link: hints }
}

if ('writeEarlyHints' in event.res) {
return event.res.writeEarlyHints(hints, callback)
return event.res.writeEarlyHints(hints, cb)
}

const headers: [string, string | string[]][] = Object.entries(hints)
if (!headers.length) {
if (callback) {
callback()
}
cb()
return
}

let hint = 'HTTP/1.1 103 Early Hints'
const [, link] = headers.find(([header]) => header.toLowerCase() === 'link') || []
if (link) {
const links = Array.isArray(link) ? link : [link]
if (hints.link) {
pi0 marked this conversation as resolved.
Show resolved Hide resolved
const links = Array.isArray(hints.link) ? hints.link : Array.from(hints.link)
pi0 marked this conversation as resolved.
Show resolved Hide resolved
hint += `\r\nLink: ${links.join('\r\n')
// TODO: remove when https://github.com/nodejs/node/pull/44874 is released
.replace(/; crossorigin/g, '').split(', ')}`
danielroe marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -124,5 +120,5 @@ export function writeEarlyHints (event: H3Event, hints: Record<string, string |
if (header.toLowerCase() === 'link') { continue }
hint += `\r\n${header}: ${value}`
}
(event.res as ServerResponse).socket!.write(`${hint}\r\n\r\n`, 'utf-8', callback)
(event.res as ServerResponse).socket!.write(`${hint}\r\n\r\n`, 'utf-8', cb)
}