Search code examples
javascriptvalidationjoi

How can I have multiple unique checks with a Joi schema validation?


I have data:

const mockScenario1 = {
  drawingNode: {
    moduleRackOutputs: [
      {
        moduleId: 'module1',
        tilt: 'tilt1',
        rack: {
          framingType: 'framing1'
        }
      },
      {
        moduleId: 'module2',
        tilt: 'tilt1',
        rack: {
          framingType: 'framing1'
        }
      }
    ]
  }
}

I want to ensure that:

  • If there are different moduleId values, I want: Only one module allowed
  • If there are different rack.framingType values, I want: Only one framing type allowed

I have this sort of started with:

Joi.object({
  drawingNode: Joi.object({
    moduleRackOutputs: Joi.array()
      .items(
        Joi.object().keys({
          moduleId: Joi.string().required(),
          tilt: Joi.string().required(),
          rack: Joi.object({
            framingType: Joi.string().required()
          })
        })
      )
      .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.'
      })
  })
})

Which works for the module, but not the framingType. Seems I can't use multiple unique?

I'd love any help or pointers. Thanks!


Solution

  • Here is the Solution. I hope it would help.

    Joi.object({
       drawingNode: Joi.object({
         moduleRackOutputs: 
         Joi.array().unique('moduleId').unique('rack.framingType')
         .messages({
            'array.unique':
            'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
            })
          })
         })
    

    OR

    Joi.object({
      drawingNode: Joi.object({
      moduleRackOutputs: Joi.array()
      .items(
        Joi.object().keys({
          moduleId: Joi.string().required(),
          tilt: Joi.string().required(),
          rack: Joi.object({
            framingType: Joi.string().required()
          })
        })
      )
      .unique((a, b) => a.moduleId === b.moduleId || a.rack.framingType === b.rack.framingType)
      .messages({
        'array.unique':
          'The drawing contains more than one module type. Multiple module types are not yet supported by the PVsyst RPA.'
       })
     })
    })