Thursday, 27 June 2019

Validating with dynamic context objects in Joi

I am needing to use a dynamic object for validation of a value. The object changes regularly so I am downloading it at runtime and saving it locally as a well-formed .json file. I need to feed these values into a call to Joi.validate (via the 'context' option) and verify that the items in an array match one of the key/value pairs in the context object.

// the defined schema
const schema = Joi.object().keys({
  'foo': Joi.array()
    .unique()
    .items(
      // these items need to match the keys/values from the context object
      Joi.object().keys({
        id: Joi.string()
          .required(), // this needs to be a key from the context object
        name: Joi.string()
          .required(), // this needs to be the value from the context object for the key defined by the above id property
      }),
    )
})

// the .json file with the context object looks as such
{
  "id of first thing": "name of first thing",
  "id of second thing": "name of second thing",
  ...
}

// validation is done like this:
Joi.validate(theThingsToValidate, schema, {context: objectFromTheJsonFile});



from Validating with dynamic context objects in Joi

No comments:

Post a Comment