gpt4 book ai didi

node.js - 当条件时 Joi 循环依赖错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:16:15 25 4
gpt4 key购买 nike

我有 3 个查询参数经度纬度半径

我有3种可能的情况:

  • 半径 - 空,经度纬度具有一些值
  • 所有 3 个参数都有值
  • 所有 3 个参数均为空

在所有其他情况下都会发送验证错误。

例如

经度=3.12 - 错误

纬度=2.12,半径=3.2 - 错误

经度=12.12,纬度=2.12 - 好的

我的架构如下所示:

const schema = Joi.object().keys({
longitude: Joi.number().optional().error(new Error('LBL_BAD_LONGITUDE'))
.when('latitude', { is: Joi.exist(), then: Joi.number().required() })
.when('radius', { is: Joi.exist(), then: Joi.number().required() }),
latitude: Joi.number().optional().error(new Error('LBL_BAD_LATITUDE'))
.when('longitude', { is: Joi.exist(), then: Joi.number().required() })
.when('radius', { is: Joi.exist(), then: Joi.number().required() }),
radius: Joi.number().optional().error(new Error('LBL_BAD_RADIUS')),
});

结果我收到错误

AssertionError [ERR_ASSERTION]: item added into group latitude created a dependencies error

知道如何验证这 3 个参数吗?

最佳答案

您的情况并不遥远。这里的技巧是根据您的经度和纬度以及某些值要求来确定。

Joi.object().keys({
radius: Joi.number(),
latitude: Joi.number().when('radius', { is: Joi.exist(), then: Joi.required() }),
longitude: Joi.number().when('radius', { is: Joi.exist(), then: Joi.required() })
}).and('latitude', 'longitude');

.and()修饰符在纬度和经度之间创建对等依赖关系;如果其中一个存在,那么另一个也必须存在。不过,省略这两个键也是有效的,因为这两个键都不是严格必需的(有助于所有 3 个参数为空)。

通过使用.and(),我们只需要根据radius是否存在添加.when()修改即可。

只有以下有效负载格式有效:

{
latitude: 1.1,
longitude: 2.2,
radius: 3
}

{
latitude: 1.1,
longitude: 2.2
}

{}

关于node.js - 当条件时 Joi 循环依赖错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55136294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com