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

fix(conform-zod): coerce file only if File class is defined #281

Merged
merged 1 commit into from
Sep 3, 2023
Merged
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
11 changes: 10 additions & 1 deletion packages/conform-zod/coercion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ export function coerceString(
* Modify the value only if it's a file, otherwise return the value as-is
*/
export function coerceFile(file: unknown) {
if (file instanceof File && file.name === '' && file.size === 0) {
if (
typeof File !== 'undefined' &&
file instanceof File &&
file.name === '' &&
file.size === 0
) {
return undefined;
}

Expand All @@ -68,6 +73,10 @@ export function coerceFile(file: unknown) {
* Check the `instanceOfType` function on zod for more info
*/
export function isFileSchema(schema: ZodEffects<any, any, any>): boolean {
if (typeof File === 'undefined') {
return false;
}

return (
schema._def.effect.type === 'refinement' &&
schema.innerType() instanceof ZodAny &&
Expand Down
7 changes: 6 additions & 1 deletion tests/conform-zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function createFormData(entries: Array<[string, string | File]>): FormData {
return formData;
}

test.beforeAll(() => {
test.beforeEach(() => {
installGlobals();
});

Expand Down Expand Up @@ -660,6 +660,11 @@ test.describe('conform-zod', () => {
},
error: {},
});

// @ts-expect-error To test if File is not defined in certain environment
delete global.File;

expect(() => parse(createFormData([]), { schema })).not.toThrow();
});

test('z.lazy', () => {
Expand Down
Loading