如何使用 Joi 确保对象数组仅包含特定键之一?

Sha*_*oon 5 javascript validation 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.'
      ])
    }
  })
Run Code Online (Sandbox Code Playgroud)

我想将其转换为Joi模式。我将如何实现这个目标?

谢谢

Ank*_*nkh 2

这可以通过以下方式完成:

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...'
    })
Run Code Online (Sandbox Code Playgroud)