icebob / fastest-validator

:zap: The fastest JS validator library for NodeJS
MIT License
1.42k stars 89 forks source link

type & $$type seem to be ambiguous in the documentation #348

Open fugufish opened 3 weeks ago

fugufish commented 3 weeks ago

The documentaiton is ambiguous about the difference between `type and $$type. For example this test on enum:

    it("allows enums in a nested schema", () => {
        const check = v.compile({type: "object", value: {$$type: "enum", values: ["a", "b", "c"]}});

        expect(check({value: "a"})).toBe(true);
        expect(check({value: "z"})).toBe(false);
    })

fails with the following result:

Cannot read properties of undefined (reading 'join')

However this

    it("allows enums in a nested schema", () => {
        const check = v.compile({type: "object", value: {type: "enum", values: ["a", "b", "c"]}});

        expect(check({value: "a"})).toBe(true);
        expect(check({value: "z"})).toBe(false);
    })

falis with

Expected: true
Received: [{"actual": undefined, "field": "type", "message": "The 'type' field is required.", "type": "required"}]

this means that $$type and type are not interchangable. $$type triggers the enum rule to be run, but the schema of the rule is changed causing it to throw an exception (i have a fix for that if needed), but type will not cause the rule to be run at all.

What is the expected behavior?

icebob commented 2 days ago

The $$type is a shorthand form for object validation schema.

Full schema:

const schema = {
    point: {
        type: "object",
        properties: {
            x: "number",
            y: "number",
        }
    },
}

Shorthand:

const schema = {
    point: {
        $$type: "object",
        x: "number",
        y: "number",
    },
}