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

Add support for input as value in v.recursive() getter #441

Merged

Conversation

Mini-ghost
Copy link
Contributor

@Mini-ghost Mini-ghost commented Feb 16, 2024

Linked issue

Resolve #440

Description

Currently, when we aim to create a valibot schema that depends on real-time data, the following code snippet is a standard approach:

const input = {
  // Your input here
};

const schema = v.recursive(() => {
  if(input.type === 'A') {
    return v.object({
      foo: v.string()
    });
  }

  return v.object({
    bar: v.number()
  });
});

const output = v.parse(schema, input);

However, this method presents challenges in abstracting the schema effectively.

If the v.recursive() function could accept a parameter—specifically, the second parameter passed to parse()—we would be able to abstract the schema with greater ease, as shown below:

// schema.ts
const schema = v.recursive((input) => {
  if(input.type === 'A') {
    return v.object({
      foo: v.string()
    });
  }

  return v.object({
    bar: v.number()
  });
});

// validate.ts
const input = {
  // Your input here
};

const output = v.parse(schema, input);

@fabian-hiller fabian-hiller self-assigned this Feb 16, 2024
@fabian-hiller fabian-hiller added the enhancement New feature or request label Feb 16, 2024
@fabian-hiller
Copy link
Owner

Thank you!

@fabian-hiller fabian-hiller merged commit 56dba92 into fabian-hiller:main Feb 18, 2024
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enable v.recursive() getter to accept a value to improving usage flexibility
2 participants