使用 Joi 和 nodeJS 验证嵌套对象中的唯一键对
Validating unique key pairs in a nested object with Joi and nodeJS
我有以下 JSON 结构:
{
key1: "value1",
key2: "value2",
transactions: [
{
receiverId: '12341',
senderId: '51634',
someOtherKey: 'value'
},
{
receiverId: '97561',
senderId: '46510',
someOtherKey: 'value'
}
]
}
我正在尝试编写一些 Joi 代码来验证交易数组中的每个对象都是唯一的,即 receiverId 和 senderId 的组合只存在一次。 transactions 数组中可以有可变数量的元素,但总是至少有 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(),
});
一个简单的方法:
const schema = Joi.object({
transactions: Joi.array()
.unique('receiverId')
.unique('senderId')
.required(),
});
这样 returns 每个字段都有一个错误(ReceivedId 有一个错误,senderId 有另一个错误)
我有以下 JSON 结构:
{
key1: "value1",
key2: "value2",
transactions: [
{
receiverId: '12341',
senderId: '51634',
someOtherKey: 'value'
},
{
receiverId: '97561',
senderId: '46510',
someOtherKey: 'value'
}
]
}
我正在尝试编写一些 Joi 代码来验证交易数组中的每个对象都是唯一的,即 receiverId 和 senderId 的组合只存在一次。 transactions 数组中可以有可变数量的元素,但总是至少有 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(),
});
一个简单的方法:
const schema = Joi.object({
transactions: Joi.array()
.unique('receiverId')
.unique('senderId')
.required(),
});
这样 returns 每个字段都有一个错误(ReceivedId 有一个错误,senderId 有另一个错误)