Skip to content

Commit

Permalink
release
Browse files Browse the repository at this point in the history
fix: formDataToObject (#17)
  • Loading branch information
sahinvardar authored Nov 28, 2024
2 parents b2db8b5 + 9cc6e78 commit e22c55d
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 23 deletions.
40 changes: 19 additions & 21 deletions src/tests/test-fixtures.ts
Original file line number Diff line number Diff line change
@@ -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<typeof SCHEMA>;

Expand Down
15 changes: 13 additions & 2 deletions src/tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
4 changes: 4 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ export function formDataToObject<TSchema extends z.ZodSchema>(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);

Expand Down

0 comments on commit e22c55d

Please sign in to comment.