Skip to content

Commit

Permalink
fix: update init function to handle nullable types and add UUID test …
Browse files Browse the repository at this point in the history
…case
  • Loading branch information
DenisBessa committed Jan 9, 2025
1 parent 9d7a1b7 commit fdada69
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
18 changes: 12 additions & 6 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ describe("make empty", () => {
expect(empty(schema)).toBeNull();
});

it("uuid", () => {
const schema = z.string().uuid();
expect(init(schema).length).toBe(36);
expect(empty(schema)).toBeNull();
});

it.each([
["", z.number(), 0],
["10-", z.number().min(10), 10],
Expand Down Expand Up @@ -228,35 +234,35 @@ describe("make empty", () => {
describe("nullable", () => {
it("string", () => {
const schema = z.string().nullable();
expect(init(schema)).toBe("");
expect(init(schema)).toBeNull();
expect(empty(schema)).toBeNull();
});
it("number", () => {
const schema = z.number().nullable();
expect(init(schema)).toBe(0);
expect(init(schema)).toBeNull();
expect(empty(schema)).toBeNull();
});
it("array", () => {
const schema = z.array(z.string()).nullable();
expect(init(schema)).toStrictEqual([]);
expect(init(schema)).toBeNull();
expect(empty(schema)).toStrictEqual([]);
});
});

describe("nullish", () => {
it("string", () => {
const schema = z.string().nullish();
expect(init(schema)).toBe("");
expect(init(schema)).toBeNull();
expect(empty(schema)).toBeNull();
});
it("number", () => {
const schema = z.number().nullish();
expect(init(schema)).toBe(0);
expect(init(schema)).toBeNull();
expect(empty(schema)).toBeNull();
});
it("array", () => {
const schema = z.array(z.string()).nullish();
expect(init(schema)).toStrictEqual([]);
expect(init(schema)).toBeNull();
expect(empty(schema)).toStrictEqual([]);
});
});
Expand Down
8 changes: 4 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import type { ZodTypeAny, input, output } from "zod";

export function init<T extends ZodTypeAny>(schema: T): output<T> {
const def = schema._def;
if (schema.isNullable() && def.typeName !== "ZodDefault") {
return null;
}

switch (def.typeName) {
case "ZodObject": {
const outputObject: Record<string, unknown> = {};
Expand Down Expand Up @@ -76,17 +80,13 @@ export function init<T extends ZodTypeAny>(schema: T): output<T> {
case "ZodNull":
case "ZodAny":
return null;
case "ZodNullable":
case "ZodOptional":
return init(def.innerType);
// case "ZodUndefined":
// case "ZodVoid":
// case "ZodUnknown":
// case "ZodNever":
default:
if (schema.isNullable()) {
return null;
}
return undefined;
}
}
Expand Down

0 comments on commit fdada69

Please sign in to comment.