Open History to see the last commit
1import { decode } from 'decode-formdata'
2import { _tanstackInternalsCookie } from './utils'
3import { ServerValidateError } from './error'
4import type {
5 FormOptions,
6 ValidationError,
7 Validator,
8} from '@tanstack/form-core'
9import type { FetchFn } from '@tanstack/start'
10import type { ServerFormState } from './types'
11β
12type Ctx = Parameters<FetchFn<FormData, unknown>>[1]
13β
14type OnServerValidateFn<TFormData> = (props: {
15 value: TFormData
16}) => ValidationError
17β
18interface CreateServerValidateOptions<
19 TFormData,
20 TFormValidator extends Validator<TFormData, unknown> | undefined = undefined,
21> extends FormOptions<TFormData, TFormValidator> {
22 onServerValidate: OnServerValidateFn<TFormData>
23}
24β
25export const createServerValidate =
26 <
27 TFormData,
28 TFormValidator extends
29 | Validator<TFormData, unknown>
30 | undefined = undefined,
31 >(
32 defaultOpts: CreateServerValidateOptions<TFormData, TFormValidator>,
33 ) =>
34 async (ctx: Ctx, formData: FormData, info?: Parameters<typeof decode>[1]) => {
35 const { validatorAdapter, onServerValidate } = defaultOpts
36β
37 const runValidator = (propsValue: { value: TFormData }) => {
38 if (validatorAdapter && typeof onServerValidate !== 'function') {
39 return validatorAdapter().validate(propsValue, onServerValidate)
40 }
41β
42 return (onServerValidate as OnServerValidateFn<TFormData>)(propsValue)
43 }
44β
45 const referer = ctx.request.headers.get('referer')!
46β
47 const data = decode(formData, info) as never as TFormData
48β
49 const onServerError = runValidator({ value: data })
50β
51 if (!onServerError) return
52β
53 const formState: ServerFormState<TFormData> = {
54 errorMap: {
55 onServer: onServerError,
56 },
57 values: data,
58 errors: onServerError ? [onServerError] : [],
59 }
60β
61 const cookie = await _tanstackInternalsCookie.serialize(formState)
62β
63 throw new ServerValidateError({
64 response: new Response('ok', {
65 headers: {
66 Location: referer,
67 'Set-Cookie': cookie,
68 },
69 status: 302,
70 }),
71 formState: formState,
72 })
73 }