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

Cannot use variant together with merge #478

Closed
Karakatiza666 opened this issue Mar 11, 2024 · 1 comment
Closed

Cannot use variant together with merge #478

Karakatiza666 opened this issue Mar 11, 2024 · 1 comment
Assignees
Labels
question Further information is requested

Comments

@Karakatiza666
Copy link

Karakatiza666 commented Mar 11, 2024

I have a seemingly simple use-case where I'd like to do this:

export const authSchema = va.variant('security_protocol', [
  va.merge([
    va.object({
      security_protocol: va.literal('SASL_PLAINTEXT')
    }),
    saslPlaintextSchema // VariantSchema
  ]),
  va.merge([
    va.object({
      security_protocol: va.literal('SASL_SSL')
    }),
    sslSchema, // ObjectSchema
    saslPlaintextSchema // VariantSchema
  ])
])

But VariantSchema cannot be used inside merge(). The workaround would be to have sslSchema and saslPlaintextSchema be template functions that take a schema to merge with their internals inside their implementation, but in a case of >1 level of nesting this gets ugly quickly.

Sidenote: finally valibot has a discriminated union!

@fabian-hiller
Copy link
Owner

Yes, merge only supports object. It basically just spread its .entries into one object. This is not possible with variant.

import * as v from 'valibot';

const ObjectSchema1 = v.object({ key1: v.string() });

const ObjectSchema2 = v.object({ key2: v.number() });

// With merge
const MergedSchema1 = v.merge([ObjectSchema1, ObjectSchema2]);

// With spread
const MergedSchema2 = v.object({
  ...ObjectSchema1.entries,
  ...ObjectSchema2.entries,
});

There are many ways to construct such complex schemas. In some cases intersect may be a better option than merge. Read more here: https://valibot.dev/guides/intersections/

@fabian-hiller fabian-hiller self-assigned this Mar 11, 2024
@fabian-hiller fabian-hiller added the question Further information is requested label Mar 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants