Thursday, 26 August 2021

How to access global object property from relative property key using Joi expression

I'm trying to set a default value of a property based on a global context passed through at validate and an existing property of the object being validated. I just can't seem to use the value of the property of the object as a key for the global context.

const context = {
    letters: {
        a: 1,
        b: 2,
        c: 3,
    },
};

const s = Joi.object().keys({
    letter: Joi.string().valid(...['a', 'b', 'c']),
    num: Joi.number().default(Joi.expression('{$letters}.{letter}'))
})

const test = {
    letter: 'a',
}

console.log(s.validate(test, { context }));

Simple example above. I have an object called letters that I place into the context. The schema will look for letter, then try to set a default value for num using the global letters as the object to pull from and the letter passed in as the key. The closest I can get is { value: { letter: 'a', num: '[object Object].a' } }



from How to access global object property from relative property key using Joi expression

No comments:

Post a Comment