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

createServerFn.ts

738 lines18.8 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 TResponse extends PromiseLike<infer U>
305 ? Promise<ServerFnReturnType<TRegister, U>>
306 : TResponse extends Response
307 ? TResponse
308 : ValidateSerializableInput<TRegister, TResponse>
309​
310export type ServerFn<
311 TRegister,
312 TMethod,
313 TMiddlewares,
314 TInputValidator,
315 TResponse,
316> = (
317 ctx: ServerFnCtx<TRegister, TMethod, TMiddlewares, TInputValidator>,
318) => ServerFnReturnType<TRegister, TResponse>
319​
320export interface ServerFnCtx<
321 TRegister,
322 TMethod,
323 TMiddlewares,
324 TInputValidator,
325> {
326 method: TMethod
327 data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TInputValidator>>
328 context: Expand<AssignAllServerFnContext<TRegister, TMiddlewares, {}>>
329 signal: AbortSignal
331​
332export type CompiledFetcherFn<TRegister, TResponse> = {
333 (
334 opts: CompiledFetcherFnOptions & ServerFnBaseOptions<TRegister, Method>,
335 ): Promise<TResponse>
336 url: string
338​
339export type ServerFnBaseOptions<
340 TRegister,
341 TMethod extends Method = 'GET',
342 TResponse = unknown,
343 TMiddlewares = unknown,
344 TInputValidator = unknown,
345> = {
346 method: TMethod
347 middleware?: Constrain<
348 TMiddlewares,
349 ReadonlyArray<AnyFunctionMiddleware | AnyRequestMiddleware>
350 >
351 inputValidator?: ConstrainValidator<TRegister, TMethod, TInputValidator>
352 extractedFn?: CompiledFetcherFn<TRegister, TResponse>
353 serverFn?: ServerFn<
354 TRegister,
355 TMethod,
356 TMiddlewares,
357 TInputValidator,
358 TResponse
359 >
360 functionId: string
362​
363export type ValidateValidatorInput<
364 TRegister,
365 TMethod extends Method,
366 TInputValidator,
367> = TMethod extends 'POST'
368 ? ResolveValidatorInput<TInputValidator> extends FormData
369 ? ResolveValidatorInput<TInputValidator>
370 : ValidateSerializable<
371 ResolveValidatorInput<TInputValidator>,
372 RegisteredSerializableInput<TRegister>
373 >
374 : ValidateSerializable<
375 ResolveValidatorInput<TInputValidator>,
376 RegisteredSerializableInput<TRegister>
377 >
378​
379export type ValidateValidator<
380 TRegister,
381 TMethod extends Method,
382 TInputValidator,
383> =
384 ValidateValidatorInput<
385 TRegister,
386 TMethod,
387 TInputValidator
388 > extends infer TInput
389 ? Validator<TInput, any>
390 : never
391​
392export type ConstrainValidator<
393 TRegister,
394 TMethod extends Method,
395 TInputValidator,
396> =
397 | (unknown extends TInputValidator
398 ? TInputValidator
399 : ResolveValidatorInput<TInputValidator> extends ValidateValidator<
400 TRegister,
401 TMethod,
402 TInputValidator
403 >
404 ? TInputValidator
405 : never)
406 | ValidateValidator<TRegister, TMethod, TInputValidator>
407​
408export type AppendMiddlewares<TMiddlewares, TNewMiddlewares> =
409 TMiddlewares extends ReadonlyArray<any>
410 ? TNewMiddlewares extends ReadonlyArray<any>
411 ? readonly [...TMiddlewares, ...TNewMiddlewares]
412 : TMiddlewares
413 : TNewMiddlewares
414​
415export interface ServerFnMiddleware<
416 TRegister,
417 TMethod extends Method,
418 TMiddlewares,
419 TInputValidator,
420> {
421 middleware: <const TNewMiddlewares>(
422 middlewares: Constrain<
423 TNewMiddlewares,
424 ReadonlyArray<AnyFunctionMiddleware | AnyRequestMiddleware | AnyServerFn>
425 >,
426 ) => ServerFnAfterMiddleware<
427 TRegister,
428 TMethod,
429 AppendMiddlewares<TMiddlewares, TNewMiddlewares>,
430 TInputValidator
431 >
433​
434export interface ServerFnAfterMiddleware<
435 TRegister,
436 TMethod extends Method,
437 TMiddlewares,
438 TInputValidator,
439> extends ServerFnWithTypes<
440 TRegister,
441 TMethod,
442 TMiddlewares,
443 TInputValidator,
444 undefined
445 >,
446 ServerFnMiddleware<TRegister, TMethod, TMiddlewares, undefined>,
447 ServerFnValidator<TRegister, TMethod, TMiddlewares>,
448 ServerFnHandler<TRegister, TMethod, TMiddlewares, TInputValidator> {
449 <TNewMethod extends Method = TMethod>(options?: {
450 method?: TNewMethod
451 }): ServerFnAfterMiddleware<
452 TRegister,
453 TNewMethod,
454 TMiddlewares,
455 TInputValidator
456 >
458​
459export type ValidatorFn<TRegister, TMethod extends Method, TMiddlewares> = <
460 TInputValidator,
461>(
462 inputValidator: ConstrainValidator<TRegister, TMethod, TInputValidator>,
463) => ServerFnAfterValidator<TRegister, TMethod, TMiddlewares, TInputValidator>
464​
465export interface ServerFnValidator<
466 TRegister,
467 TMethod extends Method,
468 TMiddlewares,
469> {
470 inputValidator: ValidatorFn<TRegister, TMethod, TMiddlewares>
472​
473export interface ServerFnAfterValidator<
474 TRegister,
475 TMethod extends Method,
476 TMiddlewares,
477 TInputValidator,
478> extends ServerFnWithTypes<
479 TRegister,
480 TMethod,
481 TMiddlewares,
482 TInputValidator,
483 undefined
484 >,
485 ServerFnMiddleware<TRegister, TMethod, TMiddlewares, TInputValidator>,
486 ServerFnHandler<TRegister, TMethod, TMiddlewares, TInputValidator> {}
487​
488export interface ServerFnAfterTyper<
489 TRegister,
490 TMethod extends Method,
491 TMiddlewares,
492 TInputValidator,
493> extends ServerFnWithTypes<
494 TRegister,
495 TMethod,
496 TMiddlewares,
497 TInputValidator,
498 undefined
499 >,
500 ServerFnHandler<TRegister, TMethod, TMiddlewares, TInputValidator> {}
501​
502// Handler
503export interface ServerFnHandler<
504 TRegister,
505 TMethod extends Method,
506 TMiddlewares,
507 TInputValidator,
508> {
509 handler: <TNewResponse>(
510 fn?: ServerFn<
511 TRegister,
512 TMethod,
513 TMiddlewares,
514 TInputValidator,
515 TNewResponse
516 >,
517 ) => Fetcher<TMiddlewares, TInputValidator, TNewResponse>
519​
520export interface ServerFnBuilder<TRegister, TMethod extends Method = 'GET'>
521 extends ServerFnWithTypes<
522 TRegister,
523 TMethod,
524 undefined,
525 undefined,
526 undefined
527 >,
528 ServerFnMiddleware<TRegister, TMethod, undefined, undefined>,
529 ServerFnValidator<TRegister, TMethod, undefined>,
530 ServerFnHandler<TRegister, TMethod, undefined, undefined> {
531 options: ServerFnBaseOptions<
532 TRegister,
533 TMethod,
534 unknown,
535 undefined,
536 undefined
537 >
539​
540export interface ServerFnWithTypes<
541 in out TRegister,
542 in out TMethod extends Method,
543 in out TMiddlewares,
544 in out TInputValidator,
545 in out TResponse,
546> {
547 _types: ServerFnTypes<
548 TRegister,
549 TMethod,
550 TMiddlewares,
551 TInputValidator,
552 TResponse
553 >
554 options: ServerFnBaseOptions<
555 TRegister,
556 TMethod,
557 unknown,
558 undefined,
559 undefined
560 >
561 [TSS_SERVER_FUNCTION_FACTORY]: true
563​
564export type AnyServerFn = ServerFnWithTypes<any, any, any, any, any>
565​
566export interface ServerFnTypes<
567 in out TRegister,
568 in out TMethod extends Method,
569 in out TMiddlewares,
570 in out TInputValidator,
571 in out TResponse,
572> {
573 method: TMethod
574 middlewares: TMiddlewares
575 inputValidator: TInputValidator
576 response: TResponse
577 allServerContext: AssignAllServerFnContext<TRegister, TMiddlewares>
578 allInput: IntersectAllValidatorInputs<TMiddlewares, TInputValidator>
579 allOutput: IntersectAllValidatorOutputs<TMiddlewares, TInputValidator>
581​
582export function flattenMiddlewares(
583 middlewares: Array<AnyFunctionMiddleware | AnyRequestMiddleware>,
584): Array<AnyFunctionMiddleware | AnyRequestMiddleware> {
585 const seen = new Set<AnyFunctionMiddleware | AnyRequestMiddleware>()
586 const flattened: Array<AnyFunctionMiddleware | AnyRequestMiddleware> = []
587​
588 const recurse = (
589 middleware: Array<AnyFunctionMiddleware | AnyRequestMiddleware>,
590 ) => {
591 middleware.forEach((m) => {
592 if (m.options.middleware) {
593 recurse(m.options.middleware)
594 }
595​
596 if (!seen.has(m)) {
597 seen.add(m)
598 flattened.push(m)
599 }
600 })
601 }
602​
603 recurse(middlewares)
604​
605 return flattened
607​
608export type ServerFnMiddlewareOptions = {
609 method: Method
610 data: any
611 headers?: HeadersInit
612 signal?: AbortSignal
613 sendContext?: any
614 context?: any
615 functionId: string
617​
618export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
619 result?: unknown
620 error?: unknown
622​
623export type NextFn = (
624 ctx: ServerFnMiddlewareResult,
625) => Promise<ServerFnMiddlewareResult>
626​
627export type MiddlewareFn = (
628 ctx: ServerFnMiddlewareOptions & {
629 next: NextFn
630 },
631) => Promise<ServerFnMiddlewareResult>
632​
633export const applyMiddleware = async (
634 middlewareFn: MiddlewareFn,
635 ctx: ServerFnMiddlewareOptions,
636 nextFn: NextFn,
637) => {
638 return middlewareFn({
639 ...ctx,
640 next: (async (
641 userCtx: ServerFnMiddlewareResult | undefined = {} as any,
642 ) => {
643 // Return the next middleware
644 return nextFn({
645 ...ctx,
646 ...userCtx,
647 context: {
648 ...ctx.context,
649 ...userCtx.context,
650 },
651 sendContext: {
652 ...ctx.sendContext,
653 ...(userCtx.sendContext ?? {}),
654 },
655 headers: mergeHeaders(ctx.headers, userCtx.headers),
656 result:
657 userCtx.result !== undefined
658 ? userCtx.result
659 : userCtx instanceof Response
660 ? userCtx
661 : (ctx as any).result,
662 error: userCtx.error ?? (ctx as any).error,
663 })
664 }) as any,
665 } as any)
667​
668export function execValidator(
669 validator: AnyValidator,
670 input: unknown,
671): unknown {
672 if (validator == null) return {}
673​
674 if ('~standard' in validator) {
675 const result = validator['~standard'].validate(input)
676​
677 if (result instanceof Promise)
678 throw new Error('Async validation not supported')
679​
680 if (result.issues)
681 throw new Error(JSON.stringify(result.issues, undefined, 2))
682​
683 return result.value
684 }
685​
686 if ('parse' in validator) {
687 return validator.parse(input)
688 }
689​
690 if (typeof validator === 'function') {
691 return validator(input)
692 }
693​
694 throw new Error('Invalid validator type!')
696​
697function serverFnBaseToMiddleware(
698 options: ServerFnBaseOptions<any, any, any, any, any>,
699): AnyFunctionMiddleware {
700 return {
701 _types: undefined!,
702 options: {
703 inputValidator: options.inputValidator,
704 client: async ({ next, sendContext, ...ctx }) => {
705 const payload = {
706 ...ctx,
707 // switch the sendContext over to context
708 context: sendContext,
709 } as any
710​
711 // Execute the extracted function
712 // but not before serializing the context
713 const res = await options.extractedFn?.(payload)
714​
715 return next(res) as unknown as FunctionMiddlewareClientFnResult<
716 any,
717 any,
718 any
719 >
720 },
721 server: async ({ next, ...ctx }) => {
722 // Execute the server function
723 const result = await options.serverFn?.(ctx as TODO)
724​
725 return next({
726 ...ctx,
727 result,
728 } as any) as unknown as FunctionMiddlewareServerFnResult<
729 any,
730 any,
731 any,
732 any,
733 any
734 >
735 },
736 },
737 }