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

Support of 'when' #14

Closed
mrpsiho opened this issue Jan 30, 2019 · 17 comments
Closed

Support of 'when' #14

mrpsiho opened this issue Jan 30, 2019 · 17 comments

Comments

@mrpsiho
Copy link

mrpsiho commented Jan 30, 2019

Hi!

Many thanks for the useful library! I just want to ask if it is possible already but I am not aware of it or if it will be possible any time soon to include 'when' into json schema? I have to achieve this https://github.com/jquense/yup#mixedwhenkeys-string--arraystring-builder-object--value-schema-schema-schema somehow.

Thanks!

@MrLoh
Copy link
Collaborator

MrLoh commented Jan 30, 2019

Could you provide an example for the input and output you expect.

@kristianmandrup
Copy link
Owner

Please add whatever you need. It should be structured to make it easy to extend as needed. Currently only supports "core" functionality, not all that JSON schema can express.

@mrpsiho
Copy link
Author

mrpsiho commented Jan 31, 2019

Well, at least something simple like:

{
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "number",
      "when": {
        "name": {
          "is": true,
          "then": "required"
        }
      }
    }
  }
}

What do you think of this?

@MrLoh
Copy link
Collaborator

MrLoh commented Jan 31, 2019

It’s doable. Any pull requests are welcome. But no one can make promises when it will be implemented otherwise. I need to do some work on the library but there are some more pressing issues at first.

@kristianmandrup
Copy link
Owner

I will work on this today and add support for some basic conditions

@kristianmandrup
Copy link
Owner

@kristianmandrup
Copy link
Owner

kristianmandrup commented Mar 9, 2019

Should be enough foundation to finish simple support for when with then and otherwise.
See changes from previous commit.

@kristianmandrup
Copy link
Owner

kristianmandrup commented Mar 9, 2019

Almost got a basic implementation working. Hope that helps you.
Just needs a little more debugging and testing...

@kristianmandrup
Copy link
Owner

kristianmandrup commented Mar 10, 2019

See when.test.js

  describe("manual setup", () => {
    var inst = yup.object({
      isBig: yup.boolean(),
      count: yup.number().when("isBig", {
        is: true,
        then: yup.number().min(5),
        otherwise: yup.number().min(0)
      })
    });

    test("validate", () => {
      const result = inst.validateSync({
        isBig: true,
        count: 10
      });
      console.log({ result });

      expect(result).toBe(true);
    });
  });

  describe("use WhenCondition", () => {
    const { constraint } = whenCondition;

    console.log({ constraint });

    const count = yup.number().when(constraint);

    var inst = yup.object({
      isBig: yup.boolean(),
      count
    });

    test("validate", () => {
      const result = inst.validateSync({
        isBig: true,
        count: 10
      });

      console.log({ result });

      expect(result).toBe(true);
    });
  });

Just need to make when() function in mixed.js apply it correctly:

  when() {
    const when = this.constraints.when;
    if (!isObjectType(when)) return this;
    const { constraint } = this.createWhenConditionFor(when);

    if (!constraint) {
      this.warn(`Invalid when constraint for: ${when}`);
      return this;
    } else {
      this.logInfo(`Adding when constraint for ${this.key}`, constraint);
      // use buildConstraint or addConstraint to add when constraint (to this.base)

      this.addConstraint("when", { values: constraint, errName: "when" });
    }
    return this;
  }

@kristianmandrup
Copy link
Owner

kristianmandrup commented Mar 10, 2019

This feature is ~90-95% done now.

@kristianmandrup
Copy link
Owner

Greatly improved design now. Major refactoring, loads of unit tests. Almost there ;)

@kristianmandrup
Copy link
Owner

Now all WhenEntry tests pass, which is the core of the feature functionality. Should be smooth sailing from here... Required extensive unit testing to get "just right".

@kristianmandrup
Copy link
Owner

kristianmandrup commented Mar 10, 2019

Should be working now. Works in isolation with all tests passing.
Having a little "trouble" writing the correct schema + test combinations for using it in a full schema. Current tests all return valid results. Not sure why. Please check it out ;)

This can be used as a template/blueprint for adding similar, more advanced conditional logic!

# all tests pass
$ jest test/conditions/when-condition.test.js

# all tests pass
$ jest test/conditions/when-entry.test.js

# never invalid for current test/schema setup
$ jest test/schema-when-then.test.js

@kristianmandrup
Copy link
Owner

Now I'm adding tests for manual approach, then comparing with engine generated schema and result.

See test/schema-when-then.test.js

  describe("manual then", () => {
    const bigJson = {
      valid: {
        isBig: true,
        count: 5
      },
      invalid: {
        isBig: true,
        count: 4
      }
    };

    describe("simple", () => {
      const yupSchema = yup.object({
        isBig: yup.boolean(),
        count: yup.number().when("isBig", {
          is: true, // alternatively: (val) => val == true
          then: yup.number().min(5)
        })
      });

      const tester = createManualTester(yupSchema);

      test("valid", () => {
        tester(bigJson.valid, true);
      });

      test("invalid", () => {
        tester(bigJson.invalid, false);
      });
    });
  });

@kristianmandrup
Copy link
Owner

Finally works with the isBig example, both for manual and generated :)

@kristianmandrup
Copy link
Owner

Please test it out before I merge into master ;)

@kristianmandrup
Copy link
Owner

Released: schema-to-yup@1.9.0 on npm (note renamed to more generic name)

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