Trabajando en una API que necesita validar la estructura del objeto de solicitud entrante. Basado en otras respuestas a preguntas similares, he intentado crear una solución que no parece funcionar.
Mi código hasta ahora:
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 trueMi esquema de validación:
const OBJECT_SCHEMA = { "uuid": { "value": String, "type": String }, "rate": { "value": Number, "type": String } }¿Alguien puede señalar lo que estoy haciendo mal aquí?
Algo para empezar:
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))