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: add writeEarlyHints utility #184

Merged
merged 2 commits into from
Oct 12, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/event/event.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { IncomingMessage as NodeIncomingMessage, ServerResponse as NodeServerResponse } from 'http'
import type { IncomingMessage, ServerResponse, H3EventContext } from '../types'
import type { IncomingMessage, ServerResponse, H3EventContext, CompatibilityEvent } from '../types'
import { MIMES } from '../utils'
import { H3Response } from './response'

Expand Down Expand Up @@ -77,3 +77,15 @@ export function isEvent (input: any): input is H3Event {
export function createEvent (req: NodeIncomingMessage, res: NodeServerResponse): H3Event {
return new H3Event(req, res)
}

export function writeEarlyHints (event: CompatibilityEvent, links: string | string[], callback?: () => void) {
if (!event.res.socket && !('writeEarlyHints' in event.res)) { return }

if ('writeEarlyHints' in event.res) {
// @ts-expect-error native node 18 implementation
return event.res.writeEarlyHints(links, callback)
}

const _links = Array.isArray(links) ? links : [links]
event.res.socket!.write(`HTTP/1.1 103 Early Hints\r\nLink: ${_links.join('\r\n')}\r\n\r\n`, 'utf-8', callback)
}