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

createServerValidate.tsx

73 lines2.0 KB

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