Skip to content

Commit

Permalink
feat: add writeEarlyHints utility (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Oct 12, 2022
1 parent 87bab2c commit 7c609c6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ Instead of adding helpers to `req` and `res`, h3 exposes them as composable util
- `setResponseHeader(event, name, value)` (alias: `setHeader`)
- `appendResponseHeaders(event, headers)` (alias: `appendHeaders`)
- `appendResponseHeader(event, name, value)` (alias: `appendHeader`)
- `writeEarlyHints(event, links, callback)`
- `createError({ statusCode, statusMessage, data? })`
- `sendError(res, error, debug?)`
- `defineHandle(handle)`
Expand Down
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)
}

0 comments on commit 7c609c6

Please sign in to comment.