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

createServerFn.test-d.ts

1,018 lines26.6 KB

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 }>>>()
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 >()