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

Invalid constraints for non-nullable array #489

Open
rwysocki-equinix opened this issue Oct 2, 2023 · 3 comments
Open

Invalid constraints for non-nullable array #489

rwysocki-equinix opened this issue Oct 2, 2023 · 3 comments

Comments

@rwysocki-equinix
Copy link

When array elements are not nullable, the array validation constraints are applied not to array, but each element
I've modified an existing zod testcase which now fails to visualize this problem:

  it('list field non-null', async () => {
    const schema = buildSchema(/* GraphQL */ `
      input UserCreateInput {
        profile: [String!]! @constraint(minLength: 1, maxLength: 5000)
      }

      directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION
    `);
    const result = await plugin(
        schema,
        [],
        {
          schema: 'zod',
          directives: {
            constraint: {
              minLength: ['min', '$1', 'Please input more than $1'],
              maxLength: ['max', '$1', 'Please input less than $1'],
            },
          },
        },
        {}
    );
    const wantContains = [
      'export function UserCreateInputSchema(): z.ZodObject<Properties<UserCreateInput>>',
      'profile: z.array(z.string()).min(1, "Please input more than 1").max(5000, "Please input less than 5000")',
    ];
    for (const wantContain of wantContains) {
      expect(result.content).toContain(wantContain);
    }
  });
@Code-Hex
Copy link
Owner

Code-Hex commented Dec 9, 2023

@rwysocki-equinix Could you send me PR for this fix?

@ashar-nadeem-lumi
Copy link

Bumping this, is there any workaround? Or a way to enforce a min length on the zod array ?

@llwire
Copy link

llwire commented Nov 15, 2024

Bumping this again.

There is actually no scenario produces a near-desired outcome.

[String!]! @constraint(min: 5) produces z.array(z.string().min(5))

[String]! @constraint(min: 5) produces z.array(z.string().nullable())

[String!] @constraint(min: 5) produces z.array(z.string().min(1).max(5)).min(1).max(5).nullish()

[String] @constraint(min: 5) produces z.array(z.string().nullable()).min(1).max(5).nullish()

The last one might be the closest but making the array entries nullable isn't great when you generate a client-side schema.

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

4 participants