如何确保对象数组仅包含一个带有 Joi 的特定键?
How can I ensure that an array of objects contains only one of a particular key with Joi?
我有类似的东西:
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.'
])
}
})
我想将其转换为 Joi
模式。我将如何做到这一点?
谢谢
您可以使用 Joi.array 方法并只向它传递您希望对象具有的一个键
const schema = Joi.object({
arrayObjects: Joi.array().items(
Joi
.object()
.keys(
{keyElement:Joi.string()}
)
)
});
这可以通过以下方式完成:
Joi.array()
.items(
Joi.object().keys({
moduleId: Joi.string().required(),
framingType: Joi.string().required()
})
)
.unique((a, b) => a.moduleId !== b.moduleId)
.message({
'array.unique': 'The drawing contains more than one module type...'
})
.unique((a, b) => a.framingType !== b.framingType)
.message({
'array.unique': 'The drawing contains more than one framing type...'
})
我有类似的东西:
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.'
])
}
})
我想将其转换为 Joi
模式。我将如何做到这一点?
谢谢
您可以使用 Joi.array 方法并只向它传递您希望对象具有的一个键
const schema = Joi.object({
arrayObjects: Joi.array().items(
Joi
.object()
.keys(
{keyElement:Joi.string()}
)
)
});
这可以通过以下方式完成:
Joi.array()
.items(
Joi.object().keys({
moduleId: Joi.string().required(),
framingType: Joi.string().required()
})
)
.unique((a, b) => a.moduleId !== b.moduleId)
.message({
'array.unique': 'The drawing contains more than one module type...'
})
.unique((a, b) => a.framingType !== b.framingType)
.message({
'array.unique': 'The drawing contains more than one framing type...'
})