Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add json example #686

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 26 additions & 16 deletions packages/conform-zod/coercion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export function ifNonEmptyString(fn: (text: string) => unknown) {
export function enableTypeCoercion<Schema extends ZodTypeAny>(
type: Schema,
cache = new Map<ZodTypeAny, ZodTypeAny>(),
parentType: ZodTypeAny | null = null,
): ZodType<output<Schema>> {
const result = cache.get(type);

Expand Down Expand Up @@ -153,6 +154,11 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
} else if (def.typeName === 'ZodArray') {
schema = any()
.transform((value) => {
// If the parent type is a union, skip auto coercion
if (parentType?._def.typeName === 'ZodUnion') {
return value;
}

// No preprocess needed if the value is already an array
if (Array.isArray(value)) {
return value;
Expand All @@ -171,15 +177,15 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
.pipe(
new ZodArray({
...def,
type: enableTypeCoercion(def.type, cache),
type: enableTypeCoercion(def.type, cache, type),
}),
);
} else if (def.typeName === 'ZodObject') {
const shape = Object.fromEntries(
Object.entries(def.shape()).map(([key, def]) => [
key,
// @ts-expect-error see message above
enableTypeCoercion(def, cache),
enableTypeCoercion(def, cache, type),
]),
);
schema = new ZodObject({
Expand All @@ -194,7 +200,7 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
} else {
schema = new ZodEffects({
...def,
schema: enableTypeCoercion(def.schema, cache),
schema: enableTypeCoercion(def.schema, cache, type),
});
}
} else if (def.typeName === 'ZodOptional') {
Expand All @@ -203,7 +209,7 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
.pipe(
new ZodOptional({
...def,
innerType: enableTypeCoercion(def.innerType, cache),
innerType: enableTypeCoercion(def.innerType, cache, type),
}),
);
} else if (def.typeName === 'ZodDefault') {
Expand All @@ -212,61 +218,65 @@ export function enableTypeCoercion<Schema extends ZodTypeAny>(
.pipe(
new ZodDefault({
...def,
innerType: enableTypeCoercion(def.innerType, cache),
innerType: enableTypeCoercion(def.innerType, cache, type),
}),
);
} else if (def.typeName === 'ZodCatch') {
schema = new ZodCatch({
...def,
innerType: enableTypeCoercion(def.innerType, cache),
innerType: enableTypeCoercion(def.innerType, cache, type),
});
} else if (def.typeName === 'ZodIntersection') {
schema = new ZodIntersection({
...def,
left: enableTypeCoercion(def.left, cache),
right: enableTypeCoercion(def.right, cache),
left: enableTypeCoercion(def.left, cache, type),
right: enableTypeCoercion(def.right, cache, type),
});
} else if (def.typeName === 'ZodUnion') {
schema = new ZodUnion({
...def,
options: def.options.map((option: ZodTypeAny) =>
enableTypeCoercion(option, cache),
enableTypeCoercion(option, cache, type),
),
});
} else if (def.typeName === 'ZodDiscriminatedUnion') {
schema = new ZodDiscriminatedUnion({
...def,
options: def.options.map((option: ZodTypeAny) =>
enableTypeCoercion(option, cache),
enableTypeCoercion(option, cache, type),
),
optionsMap: new Map(
Array.from(def.optionsMap.entries()).map(([discriminator, option]) => [
discriminator,
enableTypeCoercion(option, cache) as ZodDiscriminatedUnionOption<any>,
enableTypeCoercion(
option,
cache,
type,
) as ZodDiscriminatedUnionOption<any>,
]),
),
});
} else if (def.typeName === 'ZodTuple') {
schema = new ZodTuple({
...def,
items: def.items.map((item: ZodTypeAny) =>
enableTypeCoercion(item, cache),
enableTypeCoercion(item, cache, type),
),
});
} else if (def.typeName === 'ZodNullable') {
schema = new ZodNullable({
...def,
innerType: enableTypeCoercion(def.innerType, cache),
innerType: enableTypeCoercion(def.innerType, cache, type),
});
} else if (def.typeName === 'ZodPipeline') {
schema = new ZodPipeline({
...def,
in: enableTypeCoercion(def.in, cache),
out: enableTypeCoercion(def.out, cache),
in: enableTypeCoercion(def.in, cache, type),
out: enableTypeCoercion(def.out, cache, type),
});
} else if (def.typeName === 'ZodLazy') {
const inner = def.getter();
schema = lazy(() => enableTypeCoercion(inner, cache));
schema = lazy(() => enableTypeCoercion(inner, cache, type));
}

if (type !== schema) {
Expand Down
89 changes: 89 additions & 0 deletions playground/app/routes/parse-with-zod.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { getFormProps, getInputProps, useForm } from '@conform-to/react';
import { parseWithZod } from '@conform-to/zod';
import {
type LoaderFunctionArgs,
type ActionFunctionArgs,
json,
} from '@remix-run/node';
import { Form, useActionData, useLoaderData } from '@remix-run/react';
import { Playground, Field } from '~/components';
import { z } from 'zod';

const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
type Literal = z.infer<typeof literalSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const jsonSchema: z.ZodType<Json> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]),
);

const schema = z.object({
username: z.string().min(3, 'Username is too short'),
profile: z
.string({ required_error: 'required' })
.transform((json, ctx) => {
if (typeof json === 'string') {
try {
return JSON.parse(json);
} catch (error) {
ctx.addIssue({
code: 'custom',
message: 'invalid',
});
return z.never;
}
}
})
.pipe(jsonSchema),
});

export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);

return {
noClientValidate: url.searchParams.get('noClientValidate') === 'yes',
};
}

export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const submission = parseWithZod(formData, {
schema,
});

if (submission.status === 'success') {
// eslint-disable-next-line no-console
console.log(submission.value);
}

return json(submission.reply());
}

export default function Example() {
const { noClientValidate } = useLoaderData<typeof loader>();
const lastResult = useActionData<typeof action>();
const [form, fields] = useForm({
lastResult,
defaultValue: {
username: 'test',
profile: JSON.stringify({
age: 35,
}),
},
onValidate: !noClientValidate
? ({ formData }) => parseWithZod(formData, { schema })
: undefined,
});

return (
<Form method="post" {...getFormProps(form)}>
<Playground title="Parse with zod" result={lastResult}>
<Field label="Username" meta={fields.username}>
<input {...getInputProps(fields.username, { type: 'text' })} />
</Field>
<Field label="Profile" meta={fields.profile}>
<input {...getInputProps(fields.profile, { type: 'text' })} />
</Field>
</Playground>
</Form>
);
}
86 changes: 86 additions & 0 deletions tests/conform-zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1103,6 +1103,92 @@ describe('conform-zod', () => {
reply: expect.any(Function),
});
});

test('json schema', () => {
// Copied from https://github.com/colinhacks/zod?tab=readme-ov-file#json-type
const literalSchema = z.union([
z.string(),
z.number(),
z.boolean(),
z.null(),
]);
type Literal = z.infer<typeof literalSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const jsonSchema: z.ZodType<Json> = z.lazy(() =>
z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]),
);
const schema = z.object({
example: z
.string({ required_error: 'required' })
.transform((json, ctx) => {
if (typeof json === 'string') {
try {
return JSON.parse(json);
} catch (error) {
ctx.addIssue({
code: 'custom',
message: 'invalid',
});
return z.never;
}
}
})
.pipe(jsonSchema),
});

expect(
parseWithZod(createFormData([['example', '']]), { schema }),
).toEqual({
status: 'error',
payload: {
example: '',
},
error: {
example: ['required'],
},
reply: expect.any(Function),
});
expect(
parseWithZod(createFormData([['example', 'abc']]), { schema }),
).toEqual({
status: 'error',
payload: {
example: 'abc',
},
error: {
example: ['invalid'],
},
reply: expect.any(Function),
});
expect(
parseWithZod(
createFormData([
[
'example',
JSON.stringify({ test: 'hello world', number: 123, flag: false }),
],
]),
{ schema },
),
).toEqual({
status: 'success',
payload: {
example: JSON.stringify({
test: 'hello world',
number: 123,
flag: false,
}),
},
value: {
example: {
test: 'hello world',
number: 123,
flag: false,
},
},
reply: expect.any(Function),
});
});
});

test('parseWithZod with errorMap', () => {
Expand Down
Loading