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

Combining multiple schemas #232

Closed
cfteric opened this issue Jun 8, 2018 · 3 comments
Closed

Combining multiple schemas #232

cfteric opened this issue Jun 8, 2018 · 3 comments

Comments

@cfteric
Copy link

cfteric commented Jun 8, 2018

Hi,

I'm trying to combine several schemas into 1 and the documentation mentioned that only 2 schemas can be combined using "concat"

I have kind of achieved it by chaining "concat" after one another but I'm wondering if there's a more elegant of achieving it.

Here is the example:

import * as Yup from 'yup'

const isRequired = 1
const isMin = 1

/* Default */
const stringSchema = Yup.string()
const policySchema = Yup.string().matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])/)

/* Optional */
const isRequiredSchema = Yup.string().required()
const minSchema = Yup.string().min(9)

/* Concat */
const defaultPasswordSchema = stringSchema.concat(policySchema)

const hasRequired = defaultPasswordSchema.concat(
    isRequired === 1 ? isRequiredSchema : null)

const PasswordSchema = hasRequired.concat(
    isMin === 1 ? minSchema : null)

export default PasswordSchema
@cfteric
Copy link
Author

cfteric commented Jul 13, 2018

Apparently .concat can be chained. I managed to join multiple schemas as shown by the example below:

import * as Yup from 'yup';

const isNumber= Yup.number();
const isRequiredNumber = Yup.number().required();
const noZero = Yup.number().min(1);

const userRoleSchema= isNumber.concat(isRequiredNumber).concat(noZero);

export default userRoleSchema

@cfteric cfteric closed this as completed Jul 13, 2018
@godspeedelbow
Copy link

A generic implementation could like this:

function merge(...schemas) {
  const [first, ...rest] = schemas;

  const merged = rest.reduce(
    (mergedSchemas, schema) => mergedSchemas.concat(schema),
    first
  );

  return merged;
}

// usage:
const merged = merge(schema1, schema2, schema3, etc);

@harrygreen
Copy link

Another implementation could look like this:

const schema1 = object({
  a: string(),
  b: array(),
});
const schema2 = schema1.shape({
  b: object(),
});

schema2 will be:

const schema2 = object({
  a: string(),
  b: object(),
});

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

3 participants