Home > Software design >  How can I ensure that an array of objects contains only one of a particular key with Joi?
How can I ensure that an array of objects contains only one of a particular key with Joi?

Time:01-11

I have something like:

  let moduleId

  moduleRackOutputs.forEach((output) => {
    if (!moduleId) {
      moduleId = output.moduleId
    } else if (output.moduleId !== moduleId) {
      errors.add([
        'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
      ])
    }
  })

I want to convert this to a Joi schema. How would I accomplish this?

Thank you

CodePudding user response:

You can use the Joi.array method and pass it only one key you would like the object to have

const schema = Joi.object({
    arrayObjects: Joi.array().items(
      Joi
      .object()
      .keys(
        {keyElement:Joi.string()}
        )
     )
});

CodePudding user response:

This can be accomplished as follows:

Joi.array()
    .items(
        Joi.object().keys({
            moduleId: Joi.string().required() // moduleId type not specified
        })
    )
    .unique((a, b) => a.moduleId === b.moduleId)
    .messages({
        'array.unique': 'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
    });
  •  Tags:  
  • Related