Skip to content

Commit

Permalink
fix(conform-zod): coerce file only if file is defined
Browse files Browse the repository at this point in the history
  • Loading branch information
edmundhung committed Sep 3, 2023
1 parent c3534df commit a3a3653
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
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

0 comments on commit a3a3653

Please sign in to comment.