Joi circular dependency error with when condition

限于喜欢 提交于 2019-12-24 06:53:29

问题


I have 3 query parameters longitude, latitude, and radius.

I have 3 possible condition:

  • radius - empty, longitude and latitude with some value
  • all 3 parameters with value
  • all 3 parameters empty

In all other cases send validation error.

e.g.

longitude=3.12 - error

latitude=2.12, radius=3.2 - error

longitude=12.12, latitude=2.12 - ok

My schema look like this one:

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')),
  });

As result I get error

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

Any idea of how to validate these 3 parameters?


回答1:


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');

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).

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
}

{}


来源:https://stackoverflow.com/questions/55136294/joi-circular-dependency-error-with-when-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!