Open History to see the last commit
1import { describe, expectTypeOf, test } from 'vitest'
2import { createMiddleware } from '../createMiddleware'
3import { createServerFn } from '../createServerFn'
4import { TSS_SERVER_FUNCTION } from '../constants'
5import type { ServerFnMeta } from '../constants'
6import type {
7 Constrain,
8 Register,
9 SerializationError,
10 TsrSerializable,
11 ValidateSerializableInput,
12 Validator,
13} from '@tanstack/router-core'
14import type {
15 ConstrainValidator,
16 CustomFetch,
17 ServerFnReturnType,
18} from '../createServerFn'
19β
20test('createServerFn without middleware', () => {
21 expectTypeOf(createServerFn()).toHaveProperty('handler')
22 expectTypeOf(createServerFn()).toHaveProperty('middleware')
23 expectTypeOf(createServerFn()).toHaveProperty('validator')
24 // TODO remove upon stable
25 expectTypeOf(createServerFn()).toHaveProperty('inputValidator')
26β
27 createServerFn({ method: 'GET' }).handler((options) => {
28 expectTypeOf(options).toEqualTypeOf<{
29 context: undefined
30 data: undefined
31 method: 'GET'
32 serverFnMeta: ServerFnMeta
33 }>()
34 })
35})
36β
37test('createServerFn with validator function', () => {
38 const fnAfterValidator = createServerFn({
39 method: 'GET',
40 }).validator((input: { input: string }) => ({
41 a: input.input,
42 }))
43β
44 expectTypeOf(fnAfterValidator).toHaveProperty('handler')
45 expectTypeOf(fnAfterValidator).toHaveProperty('middleware')
46 expectTypeOf(fnAfterValidator).not.toHaveProperty('validator')
47β
48 const fn = fnAfterValidator.handler((options) => {
49 expectTypeOf(options).toEqualTypeOf<{
50 context: undefined
51 data: {
52 a: string
53 }
54 method: 'GET'
55 serverFnMeta: ServerFnMeta
56 }>()
57 })
58β
59 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
60 data: { input: string }
61 headers?: HeadersInit
62 signal?: AbortSignal
63 fetch?: CustomFetch
64 }>()
65β
66 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
67})
68β
69test('createServerFn with async validator function', () => {
70 const fnAfterValidator = createServerFn({
71 method: 'GET',
72 }).validator((input: string) => Promise.resolve(input))
73β
74 expectTypeOf(fnAfterValidator).toHaveProperty('handler')
75 expectTypeOf(fnAfterValidator).toHaveProperty('middleware')
76 expectTypeOf(fnAfterValidator).not.toHaveProperty('validator')
77β
78 const fn = fnAfterValidator.handler((options) => {
79 expectTypeOf(options).toEqualTypeOf<{
80 context: undefined
81 data: string
82 method: 'GET'
83 serverFnMeta: ServerFnMeta
84 }>()
85 })
86β
87 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
88 data: string
89 headers?: HeadersInit
90 signal?: AbortSignal
91 fetch?: CustomFetch
92 }>()
93β
94 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
95})
96β
97test('createServerFn with validator with parse method', () => {
98 const fnAfterValidator = createServerFn({
99 method: 'GET',
100 }).validator({
101 parse: (input: string) => input,
102 })
103β
104 expectTypeOf(fnAfterValidator).toHaveProperty('handler')
105 expectTypeOf(fnAfterValidator).toHaveProperty('middleware')
106 expectTypeOf(fnAfterValidator).not.toHaveProperty('validator')
107β
108 const fn = fnAfterValidator.handler((options) => {
109 expectTypeOf(options).toEqualTypeOf<{
110 context: undefined
111 data: string
112 method: 'GET'
113 serverFnMeta: ServerFnMeta
114 }>()
115 })
116β
117 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
118 data: string
119 headers?: HeadersInit
120 signal?: AbortSignal
121 fetch?: CustomFetch
122 }>()
123β
124 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
125})
126β
127test('createServerFn with async validator with parse method', () => {
128 const fnAfterValidator = createServerFn({
129 method: 'GET',
130 }).validator({
131 parse: (input: string) => Promise.resolve(input),
132 })
133β
134 expectTypeOf(fnAfterValidator).toHaveProperty('handler')
135 expectTypeOf(fnAfterValidator).toHaveProperty('middleware')
136 expectTypeOf(fnAfterValidator).not.toHaveProperty('validator')
137β
138 const fn = fnAfterValidator.handler((options) => {
139 expectTypeOf(options).toEqualTypeOf<{
140 context: undefined
141 data: string
142 method: 'GET'
143 serverFnMeta: ServerFnMeta
144 }>()
145 })
146β
147 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
148 data: string
149 headers?: HeadersInit
150 signal?: AbortSignal
151 fetch?: CustomFetch
152 }>()
153β
154 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
155})
156β
157test('createServerFn with standard validator', () => {
158 interface SyncValidator {
159 readonly '~standard': {
160 types?: {
161 input: string
162 output: string
163 }
164 validate: (input: unknown) => {
165 value: string
166 }
167 }
168 }
169 const validator: SyncValidator = {
170 ['~standard']: {
171 validate: (input: unknown) => ({
172 value: input as string,
173 }),
174 },
175 }
176β
177 const fnAfterValidator = createServerFn({
178 method: 'GET',
179 }).validator(validator)
180β
181 expectTypeOf(fnAfterValidator).toHaveProperty('handler')
182 expectTypeOf(fnAfterValidator).toHaveProperty('middleware')
183 expectTypeOf(fnAfterValidator).not.toHaveProperty('validator')
184β
185 const fn = fnAfterValidator.handler((options) => {
186 expectTypeOf(options).toEqualTypeOf<{
187 context: undefined
188 data: string
189 method: 'GET'
190 serverFnMeta: ServerFnMeta
191 }>()
192 })
193β
194 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
195 data: string
196 headers?: HeadersInit
197 signal?: AbortSignal
198 fetch?: CustomFetch
199 }>()
200β
201 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
202})
203β
204test('createServerFn with async standard validator', () => {
205 interface AsyncValidator {
206 readonly '~standard': {
207 types?: {
208 input: string
209 output: string
210 }
211 validate: (input: unknown) => Promise<{
212 value: string
213 }>
214 }
215 }
216 const validator: AsyncValidator = {
217 ['~standard']: {
218 validate: (input: unknown) =>
219 Promise.resolve({
220 value: input as string,
221 }),
222 },
223 }
224β
225 const fnAfterValidator = createServerFn({
226 method: 'GET',
227 }).validator(validator)
228β
229 expectTypeOf(fnAfterValidator).toHaveProperty('handler')
230 expectTypeOf(fnAfterValidator).toHaveProperty('middleware')
231 expectTypeOf(fnAfterValidator).not.toHaveProperty('validator')
232β
233 const fn = fnAfterValidator.handler((options) => {
234 expectTypeOf(options).toEqualTypeOf<{
235 context: undefined
236 data: string
237 method: 'GET'
238 serverFnMeta: ServerFnMeta
239 }>()
240 })
241β
242 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
243 data: string
244 headers?: HeadersInit
245 signal?: AbortSignal
246 fetch?: CustomFetch
247 }>()
248β
249 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
250})
251β
252test('createServerFn with middleware and context', () => {
253 const middleware1 = createMiddleware({ type: 'function' }).server(
254 ({ next }) => {
255 return next({ context: { a: 'a' } as const })
256 },
257 )
258β
259 const middleware2 = createMiddleware({ type: 'function' }).server(
260 ({ next }) => {
261 return next({ context: { b: 'b' } as const })
262 },
263 )
264β
265 const middleware3 = createMiddleware({ type: 'function' })
266 .middleware([middleware1, middleware2])
267 .client(({ next }) => {
268 return next({ context: { c: 'c' } as const })
269 })
270β
271 const middleware4 = createMiddleware({ type: 'function' })
272 .middleware([middleware3])
273 .client(({ context, next }) => {
274 return next({ sendContext: context })
275 })
276 .server(({ context, next }) => {
277 expectTypeOf(context).toEqualTypeOf<{
278 readonly a: 'a'
279 readonly b: 'b'
280 readonly c: 'c'
281 }>()
282 return next({ context: { d: 'd' } as const })
283 })
284β
285 const fnWithMiddleware = createServerFn({ method: 'GET' }).middleware([
286 middleware4,
287 ])
288β
289 expectTypeOf(fnWithMiddleware).toHaveProperty('handler')
290 expectTypeOf(fnWithMiddleware).toHaveProperty('validator')
291β
292 fnWithMiddleware.handler((options) => {
293 expectTypeOf(options).toEqualTypeOf<{
294 context: {
295 readonly a: 'a'
296 readonly b: 'b'
297 readonly c: 'c'
298 readonly d: 'd'
299 }
300 data: undefined
301 method: 'GET'
302 serverFnMeta: ServerFnMeta
303 }>()
304 })
305})
306β
307describe('createServerFn with middleware and validator', () => {
308 const middleware1 = createMiddleware({ type: 'function' }).validator(
309 (input: { readonly inputA: 'inputA' }) =>
310 ({
311 outputA: 'outputA',
312 }) as const,
313 )
314β
315 const middleware2 = createMiddleware({ type: 'function' }).validator(
316 (input: { readonly inputB: 'inputB' }) =>
317 ({
318 outputB: 'outputB',
319 }) as const,
320 )
321β
322 const middleware3 = createMiddleware({ type: 'function' }).middleware([
323 middleware1,
324 middleware2,
325 ])
326β
327 test(`response`, () => {
328 const fn = createServerFn({ method: 'GET' })
329 .middleware([middleware3])
330 .validator(
331 (input: { readonly inputC: 'inputC' }) =>
332 ({
333 outputC: 'outputC',
334 }) as const,
335 )
336 .handler((options) => {
337 expectTypeOf(options).toEqualTypeOf<{
338 context: undefined
339 data: {
340 readonly outputA: 'outputA'
341 readonly outputB: 'outputB'
342 readonly outputC: 'outputC'
343 }
344 method: 'GET'
345 serverFnMeta: ServerFnMeta
346 }>()
347β
348 return 'some-data' as const
349 })
350β
351 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
352 data: {
353 readonly inputA: 'inputA'
354 readonly inputB: 'inputB'
355 readonly inputC: 'inputC'
356 }
357 headers?: HeadersInit
358 signal?: AbortSignal
359 fetch?: CustomFetch
360 }>()
361β
362 expectTypeOf(fn).returns.resolves.toEqualTypeOf<'some-data'>()
363 expectTypeOf(() =>
364 fn({
365 data: { inputA: 'inputA', inputB: 'inputB', inputC: 'inputC' },
366 }),
367 ).returns.resolves.toEqualTypeOf<'some-data'>()
368 })
369})
370β
371test('createServerFn overrides properties', () => {
372 const middleware1 = createMiddleware({ type: 'function' })
373 .validator(
374 () =>
375 ({
376 input: 'a' as 'a' | 'b' | 'c',
377 }) as const,
378 )
379 .client(({ context, next }) => {
380 expectTypeOf(context).toEqualTypeOf<undefined>()
381β
382 const newContext = { context: 'a' } as const
383 return next({ sendContext: newContext, context: newContext })
384 })
385 .server(({ data, context, next }) => {
386 expectTypeOf(data).toEqualTypeOf<{ readonly input: 'a' | 'b' | 'c' }>()
387β
388 expectTypeOf(context).toEqualTypeOf<{
389 readonly context: 'a'
390 }>()
391β
392 const newContext = { context: 'b' } as const
393 return next({ sendContext: newContext, context: newContext })
394 })
395β
396 const middleware2 = createMiddleware({ type: 'function' })
397 .middleware([middleware1])
398 .validator(
399 () =>
400 ({
401 input: 'b' as 'b' | 'c',
402 }) as const,
403 )
404 .client(({ context, next }) => {
405 expectTypeOf(context).toEqualTypeOf<{ readonly context: 'a' }>()
406β
407 const newContext = { context: 'aa' } as const
408β
409 return next({ sendContext: newContext, context: newContext })
410 })
411 .server(({ context, next }) => {
412 expectTypeOf(context).toEqualTypeOf<{ readonly context: 'aa' }>()
413β
414 const newContext = { context: 'bb' } as const
415β
416 return next({ sendContext: newContext, context: newContext })
417 })
418β
419 createServerFn()
420 .middleware([middleware2])
421 .validator(
422 () =>
423 ({
424 input: 'c',
425 }) as const,
426 )
427 .handler(({ data, context }) => {
428 expectTypeOf(data).toEqualTypeOf<{
429 readonly input: 'c'
430 }>()
431 expectTypeOf(context).toEqualTypeOf<{ readonly context: 'bb' }>()
432 })
433})
434β
435test('createServerFn where validator is a primitive', () => {
436 createServerFn({ method: 'GET' })
437 .validator(() => 'c' as const)
438 .handler((options) => {
439 expectTypeOf(options).toEqualTypeOf<{
440 context: undefined
441 data: 'c'
442 method: 'GET'
443 serverFnMeta: ServerFnMeta
444 }>()
445 })
446})
447β
448test('createServerFn where validator is optional if object is optional', () => {
449 const fn = createServerFn({ method: 'GET' })
450 .validator((input: 'c' | undefined) => input)
451 .handler((options) => {
452 expectTypeOf(options).toEqualTypeOf<{
453 context: undefined
454 data: 'c' | undefined
455 method: 'GET'
456 serverFnMeta: ServerFnMeta
457 }>()
458 })
459β
460 expectTypeOf(fn).parameter(0).toEqualTypeOf<
461 | {
462 data?: 'c' | undefined
463 headers?: HeadersInit
464 signal?: AbortSignal
465 fetch?: CustomFetch
466 }
467 | undefined
468 >()
469β
470 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
471})
472β
473test('createServerFn where data is optional if there is no validator', () => {
474 const fn = createServerFn({ method: 'GET' }).handler((options) => {
475 expectTypeOf(options).toEqualTypeOf<{
476 context: undefined
477 data: undefined
478 method: 'GET'
479 serverFnMeta: ServerFnMeta
480 }>()
481 })
482β
483 expectTypeOf(fn).parameter(0).toEqualTypeOf<
484 | {
485 data?: undefined
486 headers?: HeadersInit
487 signal?: AbortSignal
488 fetch?: CustomFetch
489 }
490 | undefined
491 >()
492β
493 expectTypeOf<ReturnType<typeof fn>>().resolves.toEqualTypeOf<void>()
494})
495β
496test('createServerFn returns Date', () => {
497 const fn = createServerFn().handler(() => ({
498 dates: [new Date(), new Date()] as const,
499 }))
500β
501 expectTypeOf<ReturnType<typeof fn>>().toMatchTypeOf<Promise<unknown>>()
502 expectTypeOf<Awaited<ReturnType<typeof fn>>>().toMatchTypeOf<
503 ValidateSerializableInput<Register, { dates: readonly [Date, Date] }>
504 >()
505})
506β
507test('createServerFn returns undefined', () => {
508 const fn = createServerFn().handler(() => ({
509 nothing: undefined,
510 }))
511β
512 expectTypeOf(fn()).toEqualTypeOf<Promise<{ nothing: undefined }>>()
513})
514β
515test('createServerFn cannot return function', () => {
516 expectTypeOf(createServerFn().handler<{ func: () => 'func' }>)
517 .parameter(0)
518 .returns.toEqualTypeOf<{
519 func: SerializationError<'Function may not be serializable'>
520 }>()
521})
522β
523test('createServerFn strict false can validate and return function', () => {
524 const fn = createServerFn({ method: 'GET', strict: false })
525 .validator((input: { func: () => 'input' }) => ({
526 output: input.func(),
527 }))
528 .handler(({ data }) => {
529 expectTypeOf(data).toEqualTypeOf<{ output: 'input' }>()
530β
531 return {
532 func: () => 'func' as const,
533 }
534 })
535β
536 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
537 data: { func: () => 'input' }
538 headers?: HeadersInit
539 signal?: AbortSignal
540 fetch?: CustomFetch
541 }>()
542β
543 expectTypeOf(fn({ data: { func: () => 'input' } })).toEqualTypeOf<
544 Promise<{
545 func: () => 'func'
546 }>
547 >()
548})
549β
550test('createServerFn strict false factory preserves strictness', () => {
551 const createServerFnWithoutSerializationCheck = createServerFn({
552 strict: false,
553 })
554β
555 const myServerFn = createServerFnWithoutSerializationCheck()
556 .validator((input: { func: () => 'input' }) => ({
557 output: input.func(),
558 }))
559 .handler(({ data }) => {
560 expectTypeOf(data).toEqualTypeOf<{ output: 'input' }>()
561β
562 return {
563 func: () => 'func' as const,
564 }
565 })
566β
567 expectTypeOf(myServerFn).parameter(0).toEqualTypeOf<{
568 data: { func: () => 'input' }
569 headers?: HeadersInit
570 signal?: AbortSignal
571 fetch?: CustomFetch
572 }>()
573β
574 expectTypeOf(myServerFn({ data: { func: () => 'input' } })).toEqualTypeOf<
575 Promise<{
576 func: () => 'func'
577 }>
578 >()
579})
580β
581test('createServerFn strict input false can validate function', () => {
582 const fn = createServerFn({ strict: { input: false } })
583 .validator((input: { func: () => 'input' }) => ({
584 output: input.func(),
585 }))
586 .handler(({ data }) => {
587 expectTypeOf(data).toEqualTypeOf<{ output: 'input' }>()
588β
589 return {
590 value: 'serializable' as const,
591 }
592 })
593β
594 expectTypeOf(fn).parameter(0).toEqualTypeOf<{
595 data: { func: () => 'input' }
596 headers?: HeadersInit
597 signal?: AbortSignal
598 fetch?: CustomFetch
599 }>()
600β
601 expectTypeOf(fn({ data: { func: () => 'input' } })).toEqualTypeOf<
602 Promise<{
603 value: 'serializable'
604 }>
605 >()
606})
607β
608test('createServerFn strict output false can return function', () => {
609 const fn = createServerFn({ strict: { output: false } }).handler(() => ({
610 func: () => 'func' as const,
611 }))
612β
613 expectTypeOf(fn()).toEqualTypeOf<
614 Promise<{
615 func: () => 'func'
616 }>
617 >()
618β
619 const promiseFn = createServerFn({ strict: { output: false } }).handler(() =>
620 Promise.resolve({
621 func: () => 'func' as const,
622 }),
623 )
624β
625 expectTypeOf(promiseFn()).toEqualTypeOf<
626 Promise<{
627 func: () => 'func'
628 }>
629 >()
630})
631β
632test('ServerFnReturnType skips serialization when strict is false', () => {
633 expectTypeOf<
634 ServerFnReturnType<Register, { func: () => 'func' }, false>
635 >().toEqualTypeOf<{
636 func: () => 'func'
637 }>()
638})
639β
640test('ServerFnReturnType skips serialization when strict output is false', () => {
641 expectTypeOf<
642 ServerFnReturnType<Register, { func: () => 'func' }, { output: false }>
643 >().toEqualTypeOf<{
644 func: () => 'func'
645 }>()
646})
647β
648test('createServerFn cannot validate function', () => {
649 const validator = createServerFn().validator<
650 (input: { func: () => 'string' }) => { output: 'string' }
651 >
652β
653 expectTypeOf(validator)
654 .parameter(0)
655 .toEqualTypeOf<
656 Constrain<
657 (input: { func: () => 'string' }) => { output: 'string' },
658 Validator<
659 { func: SerializationError<'Function may not be serializable'> },
660 any
661 >
662 >
663 >()
664})
665β
666test('createServerFn strict output false still checks input', () => {
667 const validator = createServerFn({
668 method: 'GET',
669 strict: { output: false },
670 }).validator<(input: { func: () => 'string' }) => { output: 'string' }>
671β
672 expectTypeOf(validator)
673 .parameter(0)
674 .toEqualTypeOf<
675 Constrain<
676 (input: { func: () => 'string' }) => { output: 'string' },
677 Validator<
678 { func: SerializationError<'Function may not be serializable'> },
679 any
680 >
681 >
682 >()
683})
684β
685test('createServerFn can validate Date', () => {
686 const validator = createServerFn().validator<
687 (input: Date) => { output: 'string' }
688 >
689β
690 expectTypeOf(validator)
691 .parameter(0)
692 .toEqualTypeOf<
693 ConstrainValidator<Register, 'GET', (input: Date) => { output: 'string' }>
694 >()
695})
696β
697test('createServerFn can validate FormData', () => {
698 const validator = createServerFn({ method: 'POST' }).validator<
699 (input: FormData) => { output: 'string' }
700 >
701β
702 expectTypeOf(validator).parameter(0).parameter(0).toEqualTypeOf<FormData>()
703})
704β
705test('createServerFn cannot validate FormData for GET', () => {
706 const validator = createServerFn({ method: 'GET' }).validator<
707 (input: FormData) => { output: 'string' }
708 >
709β
710 expectTypeOf(validator)
711 .parameter(0)
712 .parameter(0)
713 .not.toEqualTypeOf<FormData>()
714})
715β
716describe('response', () => {
717 test(`client receives Response when Response is returned`, () => {
718 const fn = createServerFn().handler(() => {
719 return new Response('Hello World')
720 })
721β
722 expectTypeOf(fn()).toEqualTypeOf<Promise<Response>>()
723 })
724β
725 test(`client receives union when handler may return Response or string`, () => {
726 const fn = createServerFn().handler(() => {
727 const result: Response | 'Hello World' =
728 Math.random() > 0.5 ? new Response('Hello World') : 'Hello World'
729β
730 return result
731 })
732β
733 expectTypeOf(fn()).toEqualTypeOf<Promise<Response | 'Hello World'>>()
734 })
735})
736β
737test('ServerFnReturnType distributes Response union', () => {
738 expectTypeOf<
739 ServerFnReturnType<Register, Response | 'Hello World'>
740 >().toEqualTypeOf<Response | 'Hello World'>()
741})
742β
743test('createServerFn can be used as a mutation function', () => {
744 const serverFn = createServerFn()
745 .validator((data: number) => data)
746 .handler(() => 'foo')
747β
748 type MutationFunction<TData = unknown, TVariables = unknown> = (
749 variables: TVariables,
750 ) => Promise<TData>
751β
752 // simplifeid "clone" of @tansctack/react-query's useMutation
753 const useMutation = <TData, TVariables>(
754 fn: MutationFunction<TData, TVariables>,
755 ) => {}
756β
757 useMutation(serverFn)
758})
759β
760test('createServerFn validator infers unknown for default input type', () => {
761 const fn = createServerFn()
762 .validator((input) => {
763 expectTypeOf(input).toEqualTypeOf<unknown>()
764β
765 if (typeof input === 'number') return 'success' as const
766β
767 return 'failed' as const
768 })
769 .handler(({ data }) => {
770 expectTypeOf(data).toEqualTypeOf<'success' | 'failed'>()
771β
772 return data
773 })
774β
775 expectTypeOf(fn).parameter(0).toEqualTypeOf<
776 | {
777 data?: unknown | undefined
778 headers?: HeadersInit
779 signal?: AbortSignal
780 fetch?: CustomFetch
781 }
782 | undefined
783 >()
784β
785 expectTypeOf(fn()).toEqualTypeOf<Promise<'failed' | 'success'>>()
786})
787β
788test('incrementally building createServerFn with multiple middleware calls', () => {
789 const middleware1 = createMiddleware({ type: 'function' }).server(
790 ({ next }) => {
791 return next({ context: { a: 'a' } as const })
792 },
793 )
794β
795 const middleware2 = createMiddleware({ type: 'function' }).server(
796 ({ next }) => {
797 return next({ context: { b: 'b' } as const })
798 },
799 )
800β
801 const middleware3 = createMiddleware({ type: 'function' }).server(
802 ({ next }) => {
803 return next({ context: { c: 'c' } as const })
804 },
805 )
806β
807 const builderWithMw1 = createServerFn({ method: 'GET' }).middleware([
808 middleware1,
809 ])
810β
811 expectTypeOf(builderWithMw1).toHaveProperty('handler')
812 expectTypeOf(builderWithMw1).toHaveProperty('validator')
813 expectTypeOf(builderWithMw1).toHaveProperty('middleware')
814β
815 builderWithMw1.handler((options) => {
816 expectTypeOf(options).toEqualTypeOf<{
817 context: {
818 readonly a: 'a'
819 }
820 data: undefined
821 method: 'GET'
822 serverFnMeta: ServerFnMeta
823 }>()
824 })
825β
826 // overrides method
827 const builderWithMw2 = builderWithMw1({ method: 'POST' }).middleware([
828 middleware2,
829 ])
830β
831 expectTypeOf(builderWithMw2).toHaveProperty('handler')
832 expectTypeOf(builderWithMw2).toHaveProperty('validator')
833 expectTypeOf(builderWithMw2).toHaveProperty('middleware')
834β
835 builderWithMw2.handler((options) => {
836 expectTypeOf(options).toEqualTypeOf<{
837 context: {
838 readonly a: 'a'
839 readonly b: 'b'
840 }
841 data: undefined
842 method: 'POST'
843 serverFnMeta: ServerFnMeta
844 }>()
845 })
846β
847 // overrides method again
848 const builderWithMw3 = builderWithMw2({ method: 'GET' }).middleware([
849 middleware3,
850 ])
851β
852 expectTypeOf(builderWithMw3).toHaveProperty('handler')
853 expectTypeOf(builderWithMw3).toHaveProperty('validator')
854 expectTypeOf(builderWithMw3).toHaveProperty('middleware')
855β
856 builderWithMw3.handler((options) => {
857 expectTypeOf(options).toEqualTypeOf<{
858 context: {
859 readonly a: 'a'
860 readonly b: 'b'
861 readonly c: 'c'
862 }
863 data: undefined
864 method: 'GET'
865β
866 serverFnMeta: ServerFnMeta
867 }>()
868 })
869})
870β
871test('compose middlewares and server function factories', () => {
872 const middleware1 = createMiddleware({ type: 'function' }).server(
873 ({ next }) => {
874 return next({ context: { a: 'a' } as const })
875 },
876 )
877β
878 const middleware2 = createMiddleware({ type: 'function' }).server(
879 ({ next }) => {
880 return next({ context: { b: 'b' } as const })
881 },
882 )
883β
884 const builderWithMw1 = createServerFn().middleware([middleware1])
885β
886 const composedBuilder = createServerFn({ method: 'GET' }).middleware([
887 middleware2,
888 builderWithMw1,
889 ])
890β
891 composedBuilder.handler((options) => {
892 expectTypeOf(options).toEqualTypeOf<{
893 context: {
894 readonly a: 'a'
895 readonly b: 'b'
896 }
897 data: undefined
898 method: 'GET'
899 serverFnMeta: ServerFnMeta
900 }>()
901 })
902})
903β
904test('createServerFn with request middleware', () => {
905 const reqMw = createMiddleware().server(({ next }) => {
906 return next()
907 })
908 const fn = createServerFn()
909 .middleware([reqMw])
910 .handler(() => ({}))
911β
912 expectTypeOf(fn()).toEqualTypeOf<Promise<{}>>()
913})
914β
915test('createServerFn with request middleware and function middleware', () => {
916 const reqMw = createMiddleware().server(({ next }) => {
917 return next()
918 })
919β
920 const funMw = createMiddleware({ type: 'function' })
921 .validator((x: string) => x)
922 .server(({ next }) => {
923 return next({ context: { a: 'a' } as const })
924 })
925 const fn = createServerFn()
926 .middleware([reqMw, funMw])
927 .handler(() => ({}))
928β
929 expectTypeOf(fn({ data: 'a' })).toEqualTypeOf<Promise<{}>>()
930})
931β
932test('createServerFn with validator and request middleware', () => {
933 const loggingMiddleware = createMiddleware().server(async ({ next }) => {
934 console.log('Logging middleware executed on the server')
935 const result = await next()
936 return result
937 })
938β
939 const fn = createServerFn()
940 .middleware([loggingMiddleware])
941 .validator(({ userName }: { userName: string }) => {
942 return { userName }
943 })
944 .handler(async ({ data }) => {
945 return data.userName
946 })
947β
948 expectTypeOf(fn({ data: { userName: 'test' } })).toEqualTypeOf<
949 Promise<string>
950 >()
951})
952β
953test('createServerFn has TSS_SERVER_FUNCTION symbol set', () => {
954 const fn = createServerFn().handler(() => ({}))
955 expectTypeOf(fn).toHaveProperty(TSS_SERVER_FUNCTION)
956 expectTypeOf(fn[TSS_SERVER_FUNCTION]).toEqualTypeOf<true>()
957})
958β
959test('createServerFn fetcher itself is serializable', () => {
960 const fn1 = createServerFn().handler(() => ({}))
961 const fn2 = createServerFn().handler(() => fn1)
962})
963β
964test('createServerFn returns async Response', () => {
965 const serverFn = createServerFn().handler(async () => {
966 return new Response(new Blob([JSON.stringify({ a: 1 })]), {
967 status: 200,
968 headers: {
969 'Content-Type': 'application/json',
970 },
971 })
972 })
973β
974 expectTypeOf(serverFn()).toEqualTypeOf<Promise<Response>>()
975})
976β
977test('createServerFn returns sync Response', () => {
978 const serverFn = createServerFn().handler(() => {
979 return new Response(new Blob([JSON.stringify({ a: 1 })]), {
980 status: 200,
981 headers: {
982 'Content-Type': 'application/json',
983 },
984 })
985 })
986β
987 expectTypeOf(serverFn()).toEqualTypeOf<Promise<Response>>()
988})
989β
990test('createServerFn returns async array', () => {
991 const result: Array<{ a: number }> = [{ a: 1 }]
992 const serverFn = createServerFn({ method: 'GET' }).handler(async () => {
993 return result
994 })
995β
996 expectTypeOf(serverFn()).toEqualTypeOf<Promise<Array<{ a: number }>>>()
997})
998β
999test('createServerFn returns sync array', () => {
1000 const result: Array<{ a: number }> = [{ a: 1 }]
1001 const serverFn = createServerFn({ method: 'GET' }).handler(() => {
1002 return result
1003 })
1004β
1005 expectTypeOf(serverFn()).toEqualTypeOf<Promise<Array<{ a: number }>>>()
1006})
1007β
1008test('createServerFn respects TsrSerializable', () => {
1009 type MyCustomType = { f: () => void; value: string }
1010 type MyCustomTypeSerializable = MyCustomType & TsrSerializable
1011 const fn1 = createServerFn().handler(() => {
1012 const custom: MyCustomType = { f: () => {}, value: 'test' }
1013 return { nested: { custom: custom as MyCustomTypeSerializable } }
1014 })
1015 expectTypeOf(fn1()).toEqualTypeOf<
1016 Promise<{ nested: { custom: MyCustomTypeSerializable } }>
1017 >()
1018})