JOI循环依赖错误与when条件 [英] Joi circular dependency error with when condition
问题描述
我有3个查询参数经度,纬度和半径。
I have 3 query parameters longitude, latitude, and radius.
我有3种可能的条件:
- 半径-空,经度和<具有某些值的strong>纬度
- 所有具有值的3个参数
- 所有3个参数为空
- radius - empty, longitude and latitude with some value
- all 3 parameters with value
- all 3 parameters empty
在所有其他情况下,发送验证错误。
In all other cases send validation error.
例如
经度 = 3.12-错误
longitude=3.12 - error
纬度 = 2.12,半径 = 3.2-错误
latitude=2.12, radius=3.2 - error
经度 = 12.12,纬度 = 2.12-确定
longitude=12.12, latitude=2.12 - ok
我的架构如下:
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个参数的想法?
Any idea of how to validate these 3 parameters?
推荐答案
您并不遥远。取决于您的经度和纬度,并具有一定的价值
。
You're not far off.. the trick here is to pick up on your longitude and latitude with some value
requirement.
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()
修饰符会在 latitude
和经度
;如果其中一个存在,则另一个也必须存在。但是也可以省略两个键,因为两个键都不是必需的(所有3个参数为空的帮助)。
The .and()
modifier creates a peer dependency between latitude
and longitude
; if either exists then the other must also exist. However it's also valid to omit both keys as neither are strictly required (helps with all 3 parameters empty
).
通过使用 .and()
,我们只需要根据<$ c $是否添加 .when()
修改即可。 c>半径是否存在。
By using .and()
we only need to add the .when()
modifications based on whether radius
exists or not.
仅以下有效载荷格式有效:
Only the following payload formats are valid:
{
latitude: 1.1,
longitude: 2.2,
radius: 3
}
{
latitude: 1.1,
longitude: 2.2
}
{}
这篇关于JOI循环依赖错误与when条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!