From 9cc6e787ca6a3dae9eeae870e4d16832c785fa93 Mon Sep 17 00:00:00 2001 From: Sahin Vardar Date: Thu, 28 Nov 2024 14:31:50 +0100 Subject: [PATCH] fix: formDataToObject (#17) --- src/tests/test-fixtures.ts | 40 ++++++++++++++++++-------------------- src/tests/utils.test.ts | 15 ++++++++++++-- src/utils.ts | 4 ++++ 3 files changed, 36 insertions(+), 23 deletions(-) diff --git a/src/tests/test-fixtures.ts b/src/tests/test-fixtures.ts index d8619f2..d67c355 100644 --- a/src/tests/test-fixtures.ts +++ b/src/tests/test-fixtures.ts @@ -1,30 +1,28 @@ import { JSDOM } from 'jsdom'; import { z } from 'zod'; -export const SCHEMA = z - .object({ - string: z.string().optional(), - toc: z.boolean().refine(val => val === true, { - message: 'Please read and accept the terms and conditions' - }), - boolean: z.boolean(), - defaultBoolean: z.boolean(), - bigInt: z.bigint(), - number: z.number(), - stringArray: z.array(z.string()), - booleanArray: z.array(z.boolean()), +export const SCHEMA = z.object({ + string: z.string().optional(), + toc: z.boolean().refine(val => val === true, { + message: 'Please read and accept the terms and conditions' + }), + boolean: z.boolean(), + defaultBoolean: z.boolean(), + bigInt: z.bigint(), + number: z.number(), + stringArray: z.array(z.string()), + booleanArray: z.array(z.boolean()), + numberArray: z.array(z.number()), + bigIntArray: z.array(z.bigint()), + enum: z.enum(['ONE', 'TWO']), + object: z.object({ + string: z.string(), numberArray: z.array(z.number()), - bigIntArray: z.array(z.bigint()), - enum: z.enum(['ONE', 'TWO']), - object: z.object({ - string: z.string(), - numberArray: z.array(z.number()), - nested: z.object({ - string: z.string() - }) + nested: z.object({ + string: z.string() }) }) - .superRefine(() => {}); +}); export type DataType = z.infer; diff --git a/src/tests/utils.test.ts b/src/tests/utils.test.ts index c56b840..1ae1d10 100644 --- a/src/tests/utils.test.ts +++ b/src/tests/utils.test.ts @@ -6,8 +6,19 @@ import { EXPECTED_DATA, SCHEMA, getFormData } from './test-fixtures.js'; describe('utils', () => { test('formDataToObject', () => { const formData = getFormData(); - const object = formDataToObject(formData, SCHEMA); - expect(object).toStrictEqual(EXPECTED_DATA); + expect(formDataToObject(formData, SCHEMA)).toStrictEqual(EXPECTED_DATA); + + const omittedData = { ...EXPECTED_DATA, number: undefined }; + delete omittedData.number; + + expect( + formDataToObject( + formData, + SCHEMA.omit({ + number: true + }) + ) + ).toStrictEqual(omittedData); }); test('objectToFormData', () => { diff --git a/src/utils.ts b/src/utils.ts index 327368a..fd8b8c0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -83,6 +83,10 @@ export function formDataToObject(formData: FormData const flatObject: any = {}; for (const [key, value] of formData.entries()) { + if (flatSchema[key] === undefined) { + continue; + } + const valueSchema = fullyUnwrap(flatSchema[key]); const zodType = zodTypeOf(valueSchema);