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

Catch/Fallback #74

Closed
FlorianDevPhynix opened this issue Aug 7, 2023 · 2 comments
Closed

Catch/Fallback #74

FlorianDevPhynix opened this issue Aug 7, 2023 · 2 comments
Assignees
Labels
enhancement New feature or request

Comments

@FlorianDevPhynix
Copy link
Contributor

zod's default() only works with undefined and not null, which this library perfectly mimics. Zod Sandbox Example

Thanks to catch() on the other hand, it is possible to have a default value when validation fails. But Valibot seems to not have catch().
It is one of the most useful functions of zod (atleast to me) and I use it a lot. Especially with react, where I want the ensure the app always has certain pieces of data.

Thanks to the simplicity of Valibot is was able to quickly write a catch method.

import type { BaseSchema, Output } from 'valibot';
import { ValiError } from 'valibot';

function Catch<TSchema extends BaseSchema>(
  schema: TSchema,
  value: Output<TSchema>,
  callback?: (err: Error) => void
): TSchema {
  return {
    ...schema,
    parse(input, info) {
      try {
        return schema.parse(input, info);
      } catch (err: any) {
        if (typeof callback === 'undefined') {
          console.error(err);
        } else {
          callback(err);
        }
        return value;
      }
    },
  };
}

Sandbox with usage examples
npm run fallback

This method could also be called fallback. I originally called it that, but to stay true to zod's naming I changed it to Catch, just not catch (reserved word).

@fabian-hiller fabian-hiller self-assigned this Aug 7, 2023
@fabian-hiller fabian-hiller added the enhancement New feature or request label Aug 7, 2023
@fabian-hiller
Copy link
Owner

Thank you very much for the hint. I will add this functionality as soon as possible. I think fallback is a good alternative name for catch.

@FlorianDevPhynix
Copy link
Contributor Author

I read some of the performance issues and the proposed changes to move away from error throwing to some form of context being passed around, might make this function more complex. Should still work very similar though, if the previous validation issues are not passed down, only up. Catching those would be almost the same.

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

No branches or pull requests

2 participants