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

Predefined methods for all fields/types in schema #3917

Open
someden opened this issue Dec 18, 2024 · 0 comments
Open

Predefined methods for all fields/types in schema #3917

someden opened this issue Dec 18, 2024 · 0 comments

Comments

@someden
Copy link

someden commented Dec 18, 2024

In my case for all fields/types in a big scheme I need to add the same methods .optional().catch(undefined)

Example:

const Schema = z.object({
    data: z.object({
        values: z.array(
            z.object({
                name: z.string().optional().catch(undefined),
                count: z.number().optional().catch(undefined),
            }).passthrough().optional().catch(undefined)
        ).optional().catch(undefined).transform((values) =>
            values?.filter((v): v is NonNullable<typeof v> => Boolean(v))
        ),
    }).passthrough().optional().catch(undefined),
    settings: z.record(z.string(), z.object({
        name: z.string().optional().catch(undefined),
        meta: z.object({
            count: z.number().optional().catch(undefined),
            type: z.enum(['custom', 'fixed']).optional().catch(undefined),
        }).passthrough().optional().catch(undefined),
    }).passthrough().optional().catch(undefined)).optional().catch(undefined),
}).passthrough().optional().catch(undefined);

Is there a way to optimise it and get rid of duplicate methods?

May be predefine some methods:

const custom = z.optional().catch(undefined);

const Schema = custom.object({
    data: custom.object({
        values: custom.array(
            custom.object({
                name: custom.string(),
                count: custom.number(),
            }).passthrough()
        ).transform((values) =>
            values?.filter((v): v is NonNullable<typeof v> => Boolean(v))
        ),
    }).passthrough(),
    settings: custom.record(custom.string(), custom.object({
        name: custom.string(),
        meta: custom.object({
            count: custom.number(),
            type: custom.enum(['custom', 'fixed']),
        }).passthrough(),
    }).passthrough()),
}).passthrough();
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