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

[Question] Accept null as input value of a schema but not as a valid output #314

Open
adelloste opened this issue Nov 20, 2024 · 0 comments

Comments

@adelloste
Copy link

adelloste commented Nov 20, 2024

I have a large schema with several nullable fields. Is there any way to generate the schema, so that the input allows null, while the output does not?

Let's say I have this auto-generated schema:

const Pet = z
    .object({
        id: z.number().int(),
        name: z.string(),
        category: Category.optional(),
        photoUrls: z.array(z.string()),
        tags: z.array(Tag).nullish(),
        status: z.enum(["available", "pending", "sold"]).nullish(),
    });

type PetValues = z.input<typeof Pet>
// {
//     id: number;
//     name: string;
//     category?: Category | undefined;
//     photoUrls: Array<string>;
//     tags?: (Array<Tag> | null) | undefined;
//     status?: ("available" | "pending" | "sold" | null) | undefined;
// };

type PetNotValid = z.output<typeof Pet>
// {
//     id: number;
//     name: string;
//     category?: Category | undefined;
//     photoUrls: Array<string>;
//     tags?: (Array<Tag> | null) | undefined;                          // <-- don't want null
//     status?: ("available" | "pending" | "sold" | null) | undefined;  // <-- don't want null
// };

I can achieve this with a transform:

const Pet = z
    .object({
        id: z.number().int(),
        name: z.string(),
        category: Category.optional(),
        photoUrls: z.array(z.string()),
        tags: z.array(Tag).nullish().transform((value) => value ?? undefined),
        status: z.enum(["available", "pending", "sold"]).nullish().transform((value) => value ?? undefined),
    });

type PetValid = z.output<typeof Pet>
// {
//     id: number;
//     name: string;
//     category?: Category | undefined;
//     photoUrls: Array<string>;
//     tags?: Array<Tag> | undefined;                          // <-- removed null
//     status?: "available" | "pending" | "sold" | undefined;  // <-- removed null
// };

In this way null values pass the validation and after tranform it to undefined, so that zod remove the fields from the output.
How can I achieve this by editing the template.hbs?

@adelloste adelloste changed the title Accept null as input value of a schema but not as a valid output [Question] Accept null as input value of a schema but not as a valid output Nov 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant