Joi循环依赖错误与when条件
Joi circular dependency error with when condition
我有 3 个查询参数 longitude、latitude 和 radius.
我有 3 个可能的条件:
- radius - 空,longitude 和 latitude 有一些值
- 所有 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 个参数吗?
离你不远了..这里的诀窍是满足你的longitude and latitude with some value
要求。
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
和 longitude
之间创建对等依赖;如果其中一个存在,那么另一个也必须存在。然而,省略两个键也是有效的,因为两者都不是严格要求的(有助于 all 3 parameters empty
)。
使用.and()
我们只需要根据radius
是否存在添加.when()
修饰即可。
只有以下负载格式有效:
{
latitude: 1.1,
longitude: 2.2,
radius: 3
}
{
latitude: 1.1,
longitude: 2.2
}
{}
我有 3 个查询参数 longitude、latitude 和 radius.
我有 3 个可能的条件:
- radius - 空,longitude 和 latitude 有一些值
- 所有 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 个参数吗?
离你不远了..这里的诀窍是满足你的longitude and latitude with some value
要求。
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
和 longitude
之间创建对等依赖;如果其中一个存在,那么另一个也必须存在。然而,省略两个键也是有效的,因为两者都不是严格要求的(有助于 all 3 parameters empty
)。
使用.and()
我们只需要根据radius
是否存在添加.when()
修饰即可。
只有以下负载格式有效:
{
latitude: 1.1,
longitude: 2.2,
radius: 3
}
{
latitude: 1.1,
longitude: 2.2
}
{}