Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

request-response.ts

338 lines8.9 KB

1import { AsyncLocalStorage } from 'node:async_hooks'
2​
3import {
4 H3Event,
5 clearSession as h3_clearSession,
6 deleteCookie as h3_deleteCookie,
7 getRequestHost as h3_getRequestHost,
8 getRequestIP as h3_getRequestIP,
9 getRequestProtocol as h3_getRequestProtocol,
10 getRequestURL as h3_getRequestURL,
11 getSession as h3_getSession,
12 getValidatedQuery as h3_getValidatedQuery,
13 parseCookies as h3_parseCookies,
14 sanitizeStatusCode as h3_sanitizeStatusCode,
15 sanitizeStatusMessage as h3_sanitizeStatusMessage,
16 sealSession as h3_sealSession,
17 setCookie as h3_setCookie,
18 toResponse as h3_toResponse,
19 unsealSession as h3_unsealSession,
20 updateSession as h3_updateSession,
21 useSession as h3_useSession,
22} from 'h3-v2'
23import type {
24 RequestHeaderMap,
25 RequestHeaderName,
26 ResponseHeaderMap,
27 ResponseHeaderName,
28 TypedHeaders,
29} from 'fetchdts'
30​
31import type { CookieSerializeOptions } from 'cookie-es'
32import type {
33 Session,
34 SessionConfig,
35 SessionData,
36 SessionManager,
37 SessionUpdate,
38} from './session'
39import type { StandardSchemaV1 } from '@standard-schema/spec'
40import type { RequestHandler } from './request-handler'
41​
42interface StartEvent {
43 h3Event: H3Event
45const eventStorage = new AsyncLocalStorage<StartEvent>()
46​
47export type { ResponseHeaderName, RequestHeaderName }
48​
49export function requestHandler<TRegister = unknown>(
50 handler: RequestHandler<TRegister>,
51) {
52 return (request: Request, requestOpts: any): Promise<Response> | Response => {
53 const h3Event = new H3Event(request)
54​
55 const response = eventStorage.run({ h3Event }, () =>
56 handler(request, requestOpts),
57 )
58 return h3_toResponse(response, h3Event)
59 }
61​
62function getH3Event() {
63 const event = eventStorage.getStore()
64 if (!event) {
65 throw new Error(
66 `No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,
67 )
68 }
69 return event.h3Event
71​
72export function getRequest(): Request {
73 const event = getH3Event()
74 return event.req
76​
77export function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {
78 // TODO `as any` not needed when fetchdts is updated
79 return getH3Event().req.headers as any
81​
82export function getRequestHeader(name: RequestHeaderName): string | undefined {
83 return getRequestHeaders().get(name) || undefined
85​
86export function getRequestIP(opts?: {
87 /**
88 * Use the X-Forwarded-For HTTP header set by proxies.
89 *
90 * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.
91 */
92 xForwardedFor?: boolean
93}) {
94 return h3_getRequestIP(getH3Event(), opts)
96​
97/**
98 * Get the request hostname.
99 *
100 * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
101 *
102 * If no host header is found, it will default to "localhost".
103 */
104export function getRequestHost(opts?: { xForwardedHost?: boolean }) {
105 return h3_getRequestHost(getH3Event(), opts)
107​
108/**
109 * Get the full incoming request URL.
110 *
111 * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
112 *
113 * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.
114 */
115export function getRequestUrl(opts?: {
116 xForwardedHost?: boolean
117 xForwardedProto?: boolean
118}) {
119 return h3_getRequestURL(getH3Event(), opts)
121​
122/**
123 * Get the request protocol.
124 *
125 * If `x-forwarded-proto` header is set to "https", it will return "https". You can disable this behavior by setting `xForwardedProto` to `false`.
126 *
127 * If protocol cannot be determined, it will default to "http".
128 */
129export function getRequestProtocol(opts?: {
130 xForwardedProto?: boolean
131}): 'http' | 'https' | (string & {}) {
132 return h3_getRequestProtocol(getH3Event(), opts)
134​
135export function setResponseHeaders(
136 headers: TypedHeaders<ResponseHeaderMap>,
137): void {
138 const event = getH3Event()
139 for (const [name, value] of Object.entries(headers)) {
140 event.res.headers.set(name, value)
141 }
143​
144export function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {
145 const event = getH3Event()
146 return event.res.headers
148​
149export function getResponseHeader(
150 name: ResponseHeaderName,
151): string | undefined {
152 const event = getH3Event()
153 return event.res.headers.get(name) || undefined
155​
156export function setResponseHeader(
157 name: ResponseHeaderName,
158 value: string | Array<string>,
159): void {
160 const event = getH3Event()
161 if (Array.isArray(value)) {
162 event.res.headers.delete(name)
163 for (const valueItem of value) {
164 event.res.headers.append(name, valueItem)
165 }
166 } else {
167 event.res.headers.set(name, value)
168 }
170export function removeResponseHeader(name: ResponseHeaderName): void {
171 const event = getH3Event()
172 event.res.headers.delete(name)
174​
175export function clearResponseHeaders(
176 headerNames?: Array<ResponseHeaderName>,
177): void {
178 const event = getH3Event()
179 // If headerNames is provided, clear only those headers
180 if (headerNames && headerNames.length > 0) {
181 for (const name of headerNames) {
182 event.res.headers.delete(name)
183 }
184 // Otherwise, clear all headers
185 } else {
186 for (const name of event.res.headers.keys()) {
187 event.res.headers.delete(name)
188 }
189 }
191​
192export function getResponseStatus(): number {
193 return getH3Event().res.status || 200
195​
196export function setResponseStatus(code?: number, text?: string): void {
197 const event = getH3Event()
198 if (code) {
199 event.res.status = h3_sanitizeStatusCode(code, event.res.status)
200 }
201 if (text) {
202 event.res.statusText = h3_sanitizeStatusMessage(text)
203 }
205​
206/**
207 * Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.
208 * @returns Object of cookie name-value pairs
209 * ```ts
210 * const cookies = getCookies()
211 * ```
212 */
213export function getCookies(): Record<string, string> {
214 const event = getH3Event()
215 return h3_parseCookies(event)
217​
218/**
219 * Get a cookie value by name.
220 * @param name Name of the cookie to get
221 * @returns {*} Value of the cookie (String or undefined)
222 * ```ts
223 * const authorization = getCookie('Authorization')
224 * ```
225 */
226export function getCookie(name: string): string | undefined {
227 return getCookies()[name] || undefined
229​
230/**
231 * Set a cookie value by name.
232 * @param name Name of the cookie to set
233 * @param value Value of the cookie to set
234 * @param options {CookieSerializeOptions} Options for serializing the cookie
235 * ```ts
236 * setCookie('Authorization', '1234567')
237 * ```
238 */
239export function setCookie(
240 name: string,
241 value: string,
242 options?: CookieSerializeOptions,
243): void {
244 const event = getH3Event()
245 h3_setCookie(event, name, value, options)
247​
248/**
249 * Remove a cookie by name.
250 * @param name Name of the cookie to delete
251 * @param serializeOptions {CookieSerializeOptions} Cookie options
252 * ```ts
253 * deleteCookie('SessionId')
254 * ```
255 */
256export function deleteCookie(
257 name: string,
258 options?: CookieSerializeOptions,
259): void {
260 const event = getH3Event()
261 h3_deleteCookie(event, name, options)
263​
264function getDefaultSessionConfig(config: SessionConfig): SessionConfig {
265 return {
266 name: 'start',
267 ...config,
268 }
270​
271/**
272 * Create a session manager for the current request.
273 */
274export function useSession<TSessionData extends SessionData = SessionData>(
275 config: SessionConfig,
276): Promise<SessionManager<TSessionData>> {
277 const event = getH3Event()
278 return h3_useSession(event, getDefaultSessionConfig(config))
280/**
281 * Get the session for the current request
282 */
283export function getSession<TSessionData extends SessionData = SessionData>(
284 config: SessionConfig,
285): Promise<Session<TSessionData>> {
286 const event = getH3Event()
287 return h3_getSession(event, getDefaultSessionConfig(config))
289​
290/**
291 * Update the session data for the current request.
292 */
293export function updateSession<TSessionData extends SessionData = SessionData>(
294 config: SessionConfig,
295 update?: SessionUpdate<TSessionData>,
296): Promise<Session<TSessionData>> {
297 const event = getH3Event()
298 return h3_updateSession(event, getDefaultSessionConfig(config), update)
300​
301/**
302 * Encrypt and sign the session data for the current request.
303 */
304export function sealSession(config: SessionConfig): Promise<string> {
305 const event = getH3Event()
306 return h3_sealSession(event, getDefaultSessionConfig(config))
308/**
309 * Decrypt and verify the session data for the current request.
310 */
311export function unsealSession(
312 config: SessionConfig,
313 sealed: string,
314): Promise<Partial<Session>> {
315 const event = getH3Event()
316 return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)
318​
319/**
320 * Clear the session data for the current request.
321 */
322export function clearSession(config: Partial<SessionConfig>): Promise<void> {
323 const event = getH3Event()
324 return h3_clearSession(event, { name: 'start', ...config })
326​
327// not public API
328export function getResponse() {
329 const event = getH3Event()
330 return event._res
332​
333// not public API (yet)
334export function getValidatedQuery<TSchema extends StandardSchemaV1>(
335 schema: StandardSchemaV1,
336): Promise<StandardSchemaV1.InferOutput<TSchema>> {
337 return h3_getValidatedQuery(getH3Event(), schema)