【问题标题】:Validating unique key pairs in a nested object with Joi and nodeJS使用 Joi 和 nodeJS 验证嵌套对象中的唯一键对
【发布时间】:2019-04-14 01:27:48
【问题描述】:

我有以下 JSON 结构:

{
  key1: "value1",
  key2: "value2",
  transactions: [
    {
      receiverId: '12341',
      senderId: '51634',
      someOtherKey: 'value'
    },
    {
      receiverId: '97561',
      senderId: '46510',
      someOtherKey: 'value'
    }
  ]
}

我正在尝试编写一些 Joi 代码来验证 transactions 数组中的每个对象都是唯一的,即 receiverId 和 senderId 的组合只存在一次。交易数组中可以有可变数量的元素,但总是至少有 1 个。 有什么想法吗?

【问题讨论】:

  • 你应该考虑分享你的尝试。

标签: javascript node.js validation joi


【解决方案1】:

您可以使用array.unique

const array_uniq_schema = Joi.array().unique((a, b) => a.receiverId === b.receiverId && a.senderId === b.senderId);

因此,对于整个对象,架构将是(假设所有属性都是必需的):

 const schema = Joi.object({
    key1: Joi.string().required(),
    key2: Joi.string().required(),
    transactions: array_uniq_schema.required(),
 });

【讨论】:

    【解决方案2】:

    一个简单的方法:

    const schema = Joi.object({
        transactions: Joi.array()
            .unique('receiverId')
            .unique('senderId')
            .required(),
    });
    

    这样,它会为每个字段返回一个错误(ReceivedId 一个错误,senderId 另一个错误)

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2016-02-19
      • 2017-08-05
      • 2021-10-10
      • 2021-04-15
      • 1970-01-01
      • 2019-03-23
      • 2020-02-21
      • 2019-04-30
      相关资源
      最近更新 更多