If we create an object by the method .from()
:
const A = shape({
foo: {
validate: v => v > 10
}
})
const a = A.from({
foo: 11
})
And the validator has been transplanted into the setter of the property foo
.
If we assign a wrong value to foo
, there will be an error.
a.foo = 5
// throw Error
// - code: VALIDATION_FAILS
// - ...
If we assign a right value:
a.foo = 20
console.log(a.foo) // prints 20
But if the object is generated by an async skema, we can't just assign the value with the =
operator, we have to use the set
method to make it asynchronously due to the limitation of the JavaScript programming language.
The statement of
=
operator always returns the value to be assigned instantly, but not the return value of the setter function.
const {shape, set} from 'skema'
const B = shape({
foo: {
set (v) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(v + 1)
}, 10)
})
}
}
})
async function run () {
const b = await B.from({
foo: 1
})
console.log(b.foo) // 2
const result = await set(b, 'foo', 10)
console.log(b.foo, result) // 11 11
}
run()