Home > Software design >  Javascript | Validate structure of object based on custom schema
Javascript | Validate structure of object based on custom schema

Time:07-07

Working on a API that needs to validate the strucutre of the incoming request object. Based on other answers to similar questions, I have tried to create a solution that doesn't seem to be working.

My code so far:

 const testObj = {
            "uuid": {
                "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
                "type": "id"
            },
            "rate": {
                "value": 0.12,
                "type": "percent"
            }
        }

        let ok = true;

        ok = testObj === OBJECT_SCHEMA; // is false. Expected to be true

My validation schema:

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}

Can aynone pinpoint what I'm doing wrong here?

CodePudding user response:

Something to get you started:

let validate = (obj, schema) =>
    typeof obj === 'object'
        ? Object.keys(schema).every(k => validate(obj[k], schema[k]))
        : obj?.constructor === schema;

//

const OBJECT_SCHEMA = {
    "uuid": {
        "value": String,
        "type": String
    },
    "rate": {
        "value": Number,
        "type": String
    }
}


testObj = {
    "uuid": {
        "value": "5481da7-8b7-22db-d326-b6a0a858ae2f",
        "type": "id"
    },
    "rate": {
        "value": 0.12,
        "type": "percent"
    }
}

console.log(validate(testObj, OBJECT_SCHEMA))
testObj.rate.value = 'foo'
console.log(validate(testObj, OBJECT_SCHEMA))
delete testObj.rate.value
console.log(validate(testObj, OBJECT_SCHEMA))

CodePudding user response:

testObj === OBJECT_SCHEMA is returning false because the value of testObj and OBJECT_SCHEMA types are equal but not values.

My recommendation would be to checkout Yup or Zod for creating a validation

  • Related