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

createServerFn.ts

736 lines18.7 KB

1import { isNotFound, isRedirect } from '@tanstack/router-core'
2import { mergeHeaders } from '@tanstack/router-core/ssr/client'
3​
4import { TSS_SERVER_FUNCTION_FACTORY } from './constants'
5import { getStartOptions } from './getStartOptions'
6import { getStartContextServerOnly } from './getStartContextServerOnly'
7import type { TSS_SERVER_FUNCTION } from './constants'
8import type {
9 AnyValidator,
10 Constrain,
11 Expand,
12 Register,
13 RegisteredSerializableInput,
14 ResolveValidatorInput,
15 ValidateSerializable,
16 ValidateSerializableInput,
17 Validator,
18} from '@tanstack/router-core'
19import type {
20 AnyFunctionMiddleware,
21 AnyRequestMiddleware,
22 AssignAllServerFnContext,
23 FunctionMiddlewareClientFnResult,
24 FunctionMiddlewareServerFnResult,
25 IntersectAllValidatorInputs,
26 IntersectAllValidatorOutputs,
27} from './createMiddleware'
28​
29type TODO = any
30​
31export type CreateServerFn<TRegister> = <
32 TMethod extends Method,
33 TResponse = unknown,
34 TMiddlewares = undefined,
35 TInputValidator = undefined,
36>(
37 options?: {
38 method?: TMethod
39 },
40 __opts?: ServerFnBaseOptions<
41 TRegister,
42 TMethod,
43 TResponse,
44 TMiddlewares,
45 TInputValidator
46 >,
47) => ServerFnBuilder<TRegister, TMethod>
48​
49export const createServerFn: CreateServerFn<Register> = (options, __opts) => {
50 const resolvedOptions = (__opts || options || {}) as ServerFnBaseOptions<
51 any,
52 any,
53 any,
54 any,
55 any
56 >
57​
58 if (typeof resolvedOptions.method === 'undefined') {
59 resolvedOptions.method = 'GET' as Method
60 }
61​
62 const res: ServerFnBuilder<Register, Method> = {
63 options: resolvedOptions as any,
64 middleware: (middleware) => {
65 // multiple calls to `middleware()` merge the middlewares with the previously supplied ones
66 // this is primarily useful for letting users create their own abstractions on top of `createServerFn`
67​
68 const newMiddleware = [...(resolvedOptions.middleware || [])]
69 middleware.map((m) => {
70 if (TSS_SERVER_FUNCTION_FACTORY in m) {
71 if (m.options.middleware) {
72 newMiddleware.push(...m.options.middleware)
73 }
74 } else {
75 newMiddleware.push(m)
76 }
77 })
78​
79 const newOptions = {
80 ...resolvedOptions,
81 middleware: newMiddleware,
82 }
83 const res = createServerFn(undefined, newOptions) as any
84 res[TSS_SERVER_FUNCTION_FACTORY] = true
85 return res
86 },
87 inputValidator: (inputValidator) => {
88 const newOptions = { ...resolvedOptions, inputValidator }
89 return createServerFn(undefined, newOptions) as any
90 },
91 handler: (...args) => {
92 // This function signature changes due to AST transformations
93 // in the babel plugin. We need to cast it to the correct
94 // function signature post-transformation
95 const [extractedFn, serverFn] = args as unknown as [
96 CompiledFetcherFn<Register, any>,
97 ServerFn<Register, Method, any, any, any>,
98 ]
99​
100 // Keep the original function around so we can use it
101 // in the server environment
102 const newOptions = { ...resolvedOptions, extractedFn, serverFn }
103​
104 const resolvedMiddleware = [
105 ...(newOptions.middleware || []),
106 serverFnBaseToMiddleware(newOptions),
107 ]
108​
109 // We want to make sure the new function has the same
110 // properties as the original function
111​
112 return Object.assign(
113 async (opts?: CompiledFetcherFnOptions) => {
114 // Start by executing the client-side middleware chain
115 return executeMiddleware(resolvedMiddleware, 'client', {
116 ...extractedFn,
117 ...newOptions,
118 data: opts?.data as any,
119 headers: opts?.headers,
120 signal: opts?.signal,
121 context: {},
122 }).then((d) => {
123 if (d.error) throw d.error
124 return d.result
125 })
126 },
127 {
128 // This copies over the URL, function ID
129 ...extractedFn,
130 // The extracted function on the server-side calls
131 // this function
132 __executeServer: async (opts: any, signal: AbortSignal) => {
133 const startContext = getStartContextServerOnly()
134 const serverContextAfterGlobalMiddlewares =
135 startContext.contextAfterGlobalMiddlewares
136 const ctx = {
137 ...extractedFn,
138 ...opts,
139 context: {
140 ...serverContextAfterGlobalMiddlewares,
141 ...opts.context,
142 },
143 signal,
144 request: startContext.request,
145 }
146​
147 return executeMiddleware(resolvedMiddleware, 'server', ctx).then(
148 (d) => ({
149 // Only send the result and sendContext back to the client
150 result: d.result,
151 error: d.error,
152 context: d.sendContext,
153 }),
154 )
155 },
156 },
157 ) as any
158 },
159 } as ServerFnBuilder<Register, Method>
160 const fun = (options?: { method?: Method }) => {
161 return {
162 ...res,
163 options: {
164 ...res.options,
165 ...options,
166 },
167 }
168 }
169 return Object.assign(fun, res) as any
171​
172export async function executeMiddleware(
173 middlewares: Array<AnyFunctionMiddleware | AnyRequestMiddleware>,
174 env: 'client' | 'server',
175 opts: ServerFnMiddlewareOptions,
176): Promise<ServerFnMiddlewareResult> {
177 const globalMiddlewares = getStartOptions()?.functionMiddleware || []
178 const flattenedMiddlewares = flattenMiddlewares([
179 ...globalMiddlewares,
180 ...middlewares,
181 ])
182​
183 const next: NextFn = async (ctx) => {
184 // Get the next middleware
185 const nextMiddleware = flattenedMiddlewares.shift()
186​
187 // If there are no more middlewares, return the context
188 if (!nextMiddleware) {
189 return ctx
190 }
191​
192 if (
193 'inputValidator' in nextMiddleware.options &&
194 nextMiddleware.options.inputValidator &&
195 env === 'server'
196 ) {
197 // Execute the middleware's input function
198 ctx.data = await execValidator(
199 nextMiddleware.options.inputValidator,
200 ctx.data,
201 )
202 }
203​
204 let middlewareFn: MiddlewareFn | undefined = undefined
205 if (env === 'client') {
206 if ('client' in nextMiddleware.options) {
207 middlewareFn = nextMiddleware.options.client as MiddlewareFn | undefined
208 }
209 }
210 // env === 'server'
211 else if ('server' in nextMiddleware.options) {
212 middlewareFn = nextMiddleware.options.server as MiddlewareFn | undefined
213 }
214​
215 if (middlewareFn) {
216 // Execute the middleware
217 return applyMiddleware(middlewareFn, ctx, async (newCtx) => {
218 return next(newCtx).catch((error: any) => {
219 if (isRedirect(error) || isNotFound(error)) {
220 return {
221 ...newCtx,
222 error,
223 }
224 }
225​
226 throw error
227 })
228 })
229 }
230​
231 return next(ctx)
232 }
233​
234 // Start the middleware chain
235 return next({
236 ...opts,
237 headers: opts.headers || {},
238 sendContext: opts.sendContext || {},
239 context: opts.context || {},
240 })
242​
243export type CompiledFetcherFnOptions = {
244 method: Method
245 data: unknown
246 headers?: HeadersInit
247 signal?: AbortSignal
248 context?: any
250​
251export type Fetcher<TMiddlewares, TInputValidator, TResponse> =
252 undefined extends IntersectAllValidatorInputs<TMiddlewares, TInputValidator>
253 ? OptionalFetcher<TMiddlewares, TInputValidator, TResponse>
254 : RequiredFetcher<TMiddlewares, TInputValidator, TResponse>
255​
256export interface FetcherBase {
257 [TSS_SERVER_FUNCTION]: true
258 url: string
259 __executeServer: (opts: {
260 method: Method
261 data: unknown
262 headers?: HeadersInit
263 context?: any
264 signal: AbortSignal
265 }) => Promise<unknown>
267​
268export interface OptionalFetcher<TMiddlewares, TInputValidator, TResponse>
269 extends FetcherBase {
270 (
271 options?: OptionalFetcherDataOptions<TMiddlewares, TInputValidator>,
272 ): Promise<Awaited<TResponse>>
274​
275export interface RequiredFetcher<TMiddlewares, TInputValidator, TResponse>
276 extends FetcherBase {
277 (
278 opts: RequiredFetcherDataOptions<TMiddlewares, TInputValidator>,
279 ): Promise<Awaited<TResponse>>
281​
282export type FetcherBaseOptions = {
283 headers?: HeadersInit
284 signal?: AbortSignal
286​
287export interface OptionalFetcherDataOptions<TMiddlewares, TInputValidator>
288 extends FetcherBaseOptions {
289 data?: Expand<IntersectAllValidatorInputs<TMiddlewares, TInputValidator>>
291​
292export interface RequiredFetcherDataOptions<TMiddlewares, TInputValidator>
293 extends FetcherBaseOptions {
294 data: Expand<IntersectAllValidatorInputs<TMiddlewares, TInputValidator>>
296​
297export type RscStream<T> = {
298 __cacheState: T
300​
301export type Method = 'GET' | 'POST'
302​
303export type ServerFnReturnType<TRegister, TResponse> =
304 Awaited<TResponse> extends Response
305 ? TResponse
306 : ValidateSerializableInput<TRegister, TResponse>
307​
308export type ServerFn<
309 TRegister,
310 TMethod,
311 TMiddlewares,
312 TInputValidator,
313 TResponse,
314> = (
315 ctx: ServerFnCtx<TRegister, TMethod, TMiddlewares, TInputValidator>,
316) => ServerFnReturnType<TRegister, TResponse>
317​
318export interface ServerFnCtx<
319 TRegister,
320 TMethod,
321 TMiddlewares,
322 TInputValidator,
323> {
324 method: TMethod
325 data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TInputValidator>>
326 context: Expand<AssignAllServerFnContext<TRegister, TMiddlewares, {}>>
327 signal: AbortSignal
329​
330export type CompiledFetcherFn<TRegister, TResponse> = {
331 (
332 opts: CompiledFetcherFnOptions & ServerFnBaseOptions<TRegister, Method>,
333 ): Promise<TResponse>
334 url: string
336​
337export type ServerFnBaseOptions<
338 TRegister,
339 TMethod extends Method = 'GET',
340 TResponse = unknown,
341 TMiddlewares = unknown,
342 TInputValidator = unknown,
343> = {
344 method: TMethod
345 middleware?: Constrain<
346 TMiddlewares,
347 ReadonlyArray<AnyFunctionMiddleware | AnyRequestMiddleware>
348 >
349 inputValidator?: ConstrainValidator<TRegister, TMethod, TInputValidator>
350 extractedFn?: CompiledFetcherFn<TRegister, TResponse>
351 serverFn?: ServerFn<
352 TRegister,
353 TMethod,
354 TMiddlewares,
355 TInputValidator,
356 TResponse
357 >
358 functionId: string
360​
361export type ValidateValidatorInput<
362 TRegister,
363 TMethod extends Method,
364 TInputValidator,
365> = TMethod extends 'POST'
366 ? ResolveValidatorInput<TInputValidator> extends FormData
367 ? ResolveValidatorInput<TInputValidator>
368 : ValidateSerializable<
369 ResolveValidatorInput<TInputValidator>,
370 RegisteredSerializableInput<TRegister>
371 >
372 : ValidateSerializable<
373 ResolveValidatorInput<TInputValidator>,
374 RegisteredSerializableInput<TRegister>
375 >
376​
377export type ValidateValidator<
378 TRegister,
379 TMethod extends Method,
380 TInputValidator,
381> =
382 ValidateValidatorInput<
383 TRegister,
384 TMethod,
385 TInputValidator
386 > extends infer TInput
387 ? Validator<TInput, any>
388 : never
389​
390export type ConstrainValidator<
391 TRegister,
392 TMethod extends Method,
393 TInputValidator,
394> =
395 | (unknown extends TInputValidator
396 ? TInputValidator
397 : ResolveValidatorInput<TInputValidator> extends ValidateValidator<
398 TRegister,
399 TMethod,
400 TInputValidator
401 >
402 ? TInputValidator
403 : never)
404 | ValidateValidator<TRegister, TMethod, TInputValidator>
405​
406export type AppendMiddlewares<TMiddlewares, TNewMiddlewares> =
407 TMiddlewares extends ReadonlyArray<any>
408 ? TNewMiddlewares extends ReadonlyArray<any>
409 ? readonly [...TMiddlewares, ...TNewMiddlewares]
410 : TMiddlewares
411 : TNewMiddlewares
412​
413export interface ServerFnMiddleware<
414 TRegister,
415 TMethod extends Method,
416 TMiddlewares,
417 TInputValidator,
418> {
419 middleware: <const TNewMiddlewares>(
420 middlewares: Constrain<
421 TNewMiddlewares,
422 ReadonlyArray<AnyFunctionMiddleware | AnyRequestMiddleware | AnyServerFn>
423 >,
424 ) => ServerFnAfterMiddleware<
425 TRegister,
426 TMethod,
427 AppendMiddlewares<TMiddlewares, TNewMiddlewares>,
428 TInputValidator
429 >
431​
432export interface ServerFnAfterMiddleware<
433 TRegister,
434 TMethod extends Method,
435 TMiddlewares,
436 TInputValidator,
437> extends ServerFnWithTypes<
438 TRegister,
439 TMethod,
440 TMiddlewares,
441 TInputValidator,
442 undefined
443 >,
444 ServerFnMiddleware<TRegister, TMethod, TMiddlewares, undefined>,
445 ServerFnValidator<TRegister, TMethod, TMiddlewares>,
446 ServerFnHandler<TRegister, TMethod, TMiddlewares, TInputValidator> {
447 <TNewMethod extends Method = TMethod>(options?: {
448 method?: TNewMethod
449 }): ServerFnAfterMiddleware<
450 TRegister,
451 TNewMethod,
452 TMiddlewares,
453 TInputValidator
454 >
456​
457export type ValidatorFn<TRegister, TMethod extends Method, TMiddlewares> = <
458 TInputValidator,
459>(
460 inputValidator: ConstrainValidator<TRegister, TMethod, TInputValidator>,
461) => ServerFnAfterValidator<TRegister, TMethod, TMiddlewares, TInputValidator>
462​
463export interface ServerFnValidator<
464 TRegister,
465 TMethod extends Method,
466 TMiddlewares,
467> {
468 inputValidator: ValidatorFn<TRegister, TMethod, TMiddlewares>
470​
471export interface ServerFnAfterValidator<
472 TRegister,
473 TMethod extends Method,
474 TMiddlewares,
475 TInputValidator,
476> extends ServerFnWithTypes<
477 TRegister,
478 TMethod,
479 TMiddlewares,
480 TInputValidator,
481 undefined
482 >,
483 ServerFnMiddleware<TRegister, TMethod, TMiddlewares, TInputValidator>,
484 ServerFnHandler<TRegister, TMethod, TMiddlewares, TInputValidator> {}
485​
486export interface ServerFnAfterTyper<
487 TRegister,
488 TMethod extends Method,
489 TMiddlewares,
490 TInputValidator,
491> extends ServerFnWithTypes<
492 TRegister,
493 TMethod,
494 TMiddlewares,
495 TInputValidator,
496 undefined
497 >,
498 ServerFnHandler<TRegister, TMethod, TMiddlewares, TInputValidator> {}
499​
500// Handler
501export interface ServerFnHandler<
502 TRegister,
503 TMethod extends Method,
504 TMiddlewares,
505 TInputValidator,
506> {
507 handler: <TNewResponse>(
508 fn?: ServerFn<
509 TRegister,
510 TMethod,
511 TMiddlewares,
512 TInputValidator,
513 TNewResponse
514 >,
515 ) => Fetcher<TMiddlewares, TInputValidator, TNewResponse>
517​
518export interface ServerFnBuilder<TRegister, TMethod extends Method = 'GET'>
519 extends ServerFnWithTypes<
520 TRegister,
521 TMethod,
522 undefined,
523 undefined,
524 undefined
525 >,
526 ServerFnMiddleware<TRegister, TMethod, undefined, undefined>,
527 ServerFnValidator<TRegister, TMethod, undefined>,
528 ServerFnHandler<TRegister, TMethod, undefined, undefined> {
529 options: ServerFnBaseOptions<
530 TRegister,
531 TMethod,
532 unknown,
533 undefined,
534 undefined
535 >
537​
538export interface ServerFnWithTypes<
539 in out TRegister,
540 in out TMethod extends Method,
541 in out TMiddlewares,
542 in out TInputValidator,
543 in out TResponse,
544> {
545 _types: ServerFnTypes<
546 TRegister,
547 TMethod,
548 TMiddlewares,
549 TInputValidator,
550 TResponse
551 >
552 options: ServerFnBaseOptions<
553 TRegister,
554 TMethod,
555 unknown,
556 undefined,
557 undefined
558 >
559 [TSS_SERVER_FUNCTION_FACTORY]: true
561​
562export type AnyServerFn = ServerFnWithTypes<any, any, any, any, any>
563​
564export interface ServerFnTypes<
565 in out TRegister,
566 in out TMethod extends Method,
567 in out TMiddlewares,
568 in out TInputValidator,
569 in out TResponse,
570> {
571 method: TMethod
572 middlewares: TMiddlewares
573 inputValidator: TInputValidator
574 response: TResponse
575 allServerContext: AssignAllServerFnContext<TRegister, TMiddlewares>
576 allInput: IntersectAllValidatorInputs<TMiddlewares, TInputValidator>
577 allOutput: IntersectAllValidatorOutputs<TMiddlewares, TInputValidator>
579​
580export function flattenMiddlewares(
581 middlewares: Array<AnyFunctionMiddleware | AnyRequestMiddleware>,
582): Array<AnyFunctionMiddleware | AnyRequestMiddleware> {
583 const seen = new Set<AnyFunctionMiddleware | AnyRequestMiddleware>()
584 const flattened: Array<AnyFunctionMiddleware | AnyRequestMiddleware> = []
585​
586 const recurse = (
587 middleware: Array<AnyFunctionMiddleware | AnyRequestMiddleware>,
588 ) => {
589 middleware.forEach((m) => {
590 if (m.options.middleware) {
591 recurse(m.options.middleware)
592 }
593​
594 if (!seen.has(m)) {
595 seen.add(m)
596 flattened.push(m)
597 }
598 })
599 }
600​
601 recurse(middlewares)
602​
603 return flattened
605​
606export type ServerFnMiddlewareOptions = {
607 method: Method
608 data: any
609 headers?: HeadersInit
610 signal?: AbortSignal
611 sendContext?: any
612 context?: any
613 functionId: string
615​
616export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
617 result?: unknown
618 error?: unknown
620​
621export type NextFn = (
622 ctx: ServerFnMiddlewareResult,
623) => Promise<ServerFnMiddlewareResult>
624​
625export type MiddlewareFn = (
626 ctx: ServerFnMiddlewareOptions & {
627 next: NextFn
628 },
629) => Promise<ServerFnMiddlewareResult>
630​
631export const applyMiddleware = async (
632 middlewareFn: MiddlewareFn,
633 ctx: ServerFnMiddlewareOptions,
634 nextFn: NextFn,
635) => {
636 return middlewareFn({
637 ...ctx,
638 next: (async (
639 userCtx: ServerFnMiddlewareResult | undefined = {} as any,
640 ) => {
641 // Return the next middleware
642 return nextFn({
643 ...ctx,
644 ...userCtx,
645 context: {
646 ...ctx.context,
647 ...userCtx.context,
648 },
649 sendContext: {
650 ...ctx.sendContext,
651 ...(userCtx.sendContext ?? {}),
652 },
653 headers: mergeHeaders(ctx.headers, userCtx.headers),
654 result:
655 userCtx.result !== undefined
656 ? userCtx.result
657 : userCtx instanceof Response
658 ? userCtx
659 : (ctx as any).result,
660 error: userCtx.error ?? (ctx as any).error,
661 })
662 }) as any,
663 } as any)
665​
666export function execValidator(
667 validator: AnyValidator,
668 input: unknown,
669): unknown {
670 if (validator == null) return {}
671​
672 if ('~standard' in validator) {
673 const result = validator['~standard'].validate(input)
674​
675 if (result instanceof Promise)
676 throw new Error('Async validation not supported')
677​
678 if (result.issues)
679 throw new Error(JSON.stringify(result.issues, undefined, 2))
680​
681 return result.value
682 }
683​
684 if ('parse' in validator) {
685 return validator.parse(input)
686 }
687​
688 if (typeof validator === 'function') {
689 return validator(input)
690 }
691​
692 throw new Error('Invalid validator type!')
694​
695function serverFnBaseToMiddleware(
696 options: ServerFnBaseOptions<any, any, any, any, any>,
697): AnyFunctionMiddleware {
698 return {
699 _types: undefined!,
700 options: {
701 inputValidator: options.inputValidator,
702 client: async ({ next, sendContext, ...ctx }) => {
703 const payload = {
704 ...ctx,
705 // switch the sendContext over to context
706 context: sendContext,
707 } as any
708​
709 // Execute the extracted function
710 // but not before serializing the context
711 const res = await options.extractedFn?.(payload)
712​
713 return next(res) as unknown as FunctionMiddlewareClientFnResult<
714 any,
715 any,
716 any
717 >
718 },
719 server: async ({ next, ...ctx }) => {
720 // Execute the server function
721 const result = await options.serverFn?.(ctx as TODO)
722​
723 return next({
724 ...ctx,
725 result,
726 } as any) as unknown as FunctionMiddlewareServerFnResult<
727 any,
728 any,
729 any,
730 any,
731 any
732 >
733 },
734 },
735 }