kristianmandrup/schema-to-yup

Support of 'when'

mrpsiho opened this issue · 17 comments

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 commented

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

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.

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 commented

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.

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

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

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

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;
  }

This feature is ~90-95% done now.

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

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".

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

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);
      });
    });
  });

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

Please test it out before I merge into master ;)

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