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...
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
moduleIdvalues, I want:Only one module allowed - If there are different
rack.framingTypevalues, 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!
1 Answer
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.'
})
})
})