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

function-middleware-headers.test.ts

234 lines7.2 KB

1import { expect, test } from 'vitest'
2import { runWithStartContext } from '@tanstack/start-storage-context'
3import { createMiddleware } from '../src/createMiddleware'
4import { executeMiddleware } from '../src/createServerFn'
5​
6function runMiddleware(
7 middlewares: Parameters<typeof executeMiddleware>[0],
8 env: 'client' | 'server',
9 headers?: HeadersInit,
10) {
11 return runWithStartContext(
12 {
13 getRouter() {
14 throw new Error('Function middleware does not need a router')
15 },
16 request: new Request('http://localhost/_serverFn/header-test'),
17 startOptions: {},
18 contextAfterGlobalMiddlewares: {},
19 executedRequestMiddlewares: new Set(),
20 handlerType: 'serverFn',
21 },
22 () =>
23 executeMiddleware(middlewares, env, {
24 method: 'POST',
25 data: undefined,
26 serverFnMeta: { id: 'header-test' },
27 context: { request: 'request-context' },
28 headers,
29 }),
30 )
32​
33test('client next() provides headers when no headers were supplied', async () => {
34 let observedHeaders: HeadersInit | undefined
35 const middleware = createMiddleware({ type: 'function' }).client(
36 async ({ next }) => {
37 const result = await next()
38 observedHeaders = result.headers
39 return result
40 },
41 )
42​
43 const result = await runMiddleware([middleware], 'client')
44​
45 expect(observedHeaders).toBeDefined()
46 expect(Array.from(new Headers(observedHeaders))).toEqual([])
47 expect(result.headers).toBe(observedHeaders)
48})
49​
50test.each([
51 ['client', 'omitted'],
52 ['server', 'omitted'],
53 ['client', 'empty'],
54 ['server', 'empty'],
55] as const)(
56 '%s next() preserves context with %s sendContext',
57 async (env, sendContext) => {
58 const options =
59 sendContext === 'omitted'
60 ? { context: { hop: 'kept' } }
61 : { context: { hop: 'kept' }, sendContext: {} }
62 const assertResult = (result: {
63 context?: unknown
64 sendContext?: unknown
65 }) => {
66 expect(result.context).toEqual({
67 request: 'request-context',
68 hop: 'kept',
69 })
70 if (sendContext === 'omitted') {
71 expect(result.sendContext).toBeUndefined()
72 } else {
73 expect(result.sendContext).toBeDefined()
74 expect(result.sendContext).toEqual({})
75 }
76 }
77 const middleware = createMiddleware({ type: 'function' })
78 .client(async ({ next }) => {
79 const result = await next(options)
80 assertResult(result)
81 return result
82 })
83 .server(async ({ next }) => {
84 const result = await next(options)
85 assertResult(result)
86 return result
87 })
88​
89 const result = await runMiddleware([middleware], env)
90​
91 expect(result.error).toBeUndefined()
92 assertResult(result)
93 },
95​
96test('server middleware preserves context and sendContext without headers', async () => {
97 const first = createMiddleware({ type: 'function' }).server(({ next }) =>
98 next({ context: { first: 'one' }, sendContext: { firstReply: 'one' } }),
99 )
100 const second = createMiddleware({ type: 'function' })
101 .middleware([first])
102 .server(({ context, next }) => {
103 expect(context.first).toBe('one')
104 return next({
105 context: { second: 'two' },
106 sendContext: { secondReply: 'two' },
107 })
108 })
109​
110 const result = await runMiddleware([second], 'server')
111​
112 expect(result.context).toEqual({
113 request: 'request-context',
114 first: 'one',
115 second: 'two',
116 })
117 expect(result.sendContext).toEqual({ firstReply: 'one', secondReply: 'two' })
118})
119​
120test.each(['client', 'server'] as const)(
121 '%s middleware preserves explicitly supplied headers',
122 async (env) => {
123 const headers = new Headers({ 'x-call': 'preserved' })
124 const middleware = createMiddleware({ type: 'function' })
125 .client(({ next }) => next())
126 .server(({ next }) => next())
127​
128 const result = await runMiddleware([middleware], env, headers)
129​
130 expect(new Headers(result.headers).get('x-call')).toBe('preserved')
131 expect(headers.get('x-call')).toBe('preserved')
132 },
134​
135test('client middleware merges supplied headers without changing either input', async () => {
136 const headers = new Headers({ 'x-initial': 'one', 'x-shared': 'initial' })
137 headers.append('set-cookie', 'first=one; Path=/')
138 const nextHeaders = new Headers({ 'x-next': 'two', 'x-shared': 'next' })
139 nextHeaders.append('set-cookie', 'second=two; Path=/')
140 const originalHeaders = Array.from(headers)
141 const originalNextHeaders = Array.from(nextHeaders)
142 const middleware = createMiddleware({ type: 'function' }).client(({ next }) =>
143 next({ headers: nextHeaders }),
144 )
145​
146 const result = await runMiddleware([middleware], 'client', headers)
147 const merged = new Headers(result.headers)
148​
149 expect(merged.get('x-initial')).toBe('one')
150 expect(merged.get('x-next')).toBe('two')
151 expect(merged.get('x-shared')).toBe('next')
152 expect(merged.getSetCookie()).toEqual([
153 'first=one; Path=/',
154 'second=two; Path=/',
155 ])
156 expect(Array.from(headers)).toEqual(originalHeaders)
157 expect(Array.from(nextHeaders)).toEqual(originalNextHeaders)
158})
159​
160test('client middleware can supply headers when the call supplied none', async () => {
161 const middleware = createMiddleware({ type: 'function' }).client(({ next }) =>
162 next({ headers: { 'x-next': 'present' } }),
163 )
164​
165 const result = await runMiddleware([middleware], 'client')
166​
167 expect(new Headers(result.headers).get('x-next')).toBe('present')
168})
169​
170test.each(['client', 'server'] as const)(
171 '%s executor reads initial middleware options in order without repeating accessors',
172 async (env) => {
173 const reads: Array<string> = []
174 const ignoredSendContext = Object.freeze({ selected: 'first read' })
175 const selectedSendContext = Object.freeze({ selected: 'second read' })
176 const context = Object.freeze({ request: 'preserved' })
177 const headers = new Headers({ 'x-initial': 'preserved' })
178 const fetch = async () => new Response('unused')
179 let sendContextReads = 0
180​
181 const result = await runWithStartContext(
182 {
183 getRouter() {
184 throw new Error('Function middleware does not need a router')
185 },
186 request: new Request('http://localhost/_serverFn/accessor-test'),
187 startOptions: {},
188 contextAfterGlobalMiddlewares: {},
189 executedRequestMiddlewares: new Set(),
190 handlerType: 'serverFn',
191 },
192 () =>
193 executeMiddleware([], env, {
194 method: 'POST',
195 data: undefined,
196 serverFnMeta: { id: 'accessor-test' },
197 get headers() {
198 reads.push('headers')
199 return headers
200 },
201 get sendContext() {
202 reads.push('sendContext')
203 sendContextReads++
204 return sendContextReads === 1
205 ? ignoredSendContext
206 : selectedSendContext
207 },
208 get context() {
209 reads.push('context')
210 return context
211 },
212 get fetch() {
213 reads.push('fetch')
214 return fetch
215 },
216 }),
217 )
218​
219 expect(reads).toEqual([
220 'headers',
221 'sendContext',
222 'context',
223 'fetch',
224 'headers',
225 'sendContext',
226 'context',
227 'fetch',
228 ])
229 expect(result.sendContext).toBe(selectedSendContext)
230 expect(result.context).toBe(context)
231 expect(result.headers).toBe(headers)
232 expect(result.fetch).toBe(fetch)
233 },