punkish
punkish

Reputation: 15268

query params dependent on other query params in hapi-swagger

I am building a hapi-swagger interface to my api. One of the query params, type, has another query param subtype that depends on the former. I have figured out how to implement Joi validation for it successfully but am not so successful with the interface. My validation code is

{
    type: Joi.string()
         .valid('image', 'publication', 'dataset')
         .optional(),

    subtype: Joi.string()
         .optional()
         .when('type', {is: 'image',       then: Joi.valid('png', 'jpg')})
         .when('type', {is: 'publication', then: Joi.valid('newspaper', 'book')})
         .description('subtype based on the file_type')
}

But the interface shows only png and jpg for subtype. Suggestions on how I could implement this so the correct subtype shows when the respective type is chosen?

Upvotes: 0

Views: 365

Answers (1)

Apurva jain
Apurva jain

Reputation: 1590

I tried something similar and it works fine for me. Please checkout my code below:

Joi.object().keys({
  billFormat: Joi.string().valid('sms', 'email').required(),
  email: Joi.string()
    .when('ebillFormat', { is: 'sms', then: Joi.valid('a', 'b') })
    .when('ebillFormat', { is: 'email', then: Joi.valid('c', 'd') }),
});

And my payload looks like below:

{
    "ebillFormat": "email",
    "email": "hello"
}

The error I get is as follows:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "child \"email\" fails because [\"email\" must be one of [c, d]]",
    "validation": {
        "source": "payload",
        "keys": [
            "email"
        ]
    }
}

Please let me know what exactly you are trying to achieve and what issue are you facing.

Upvotes: 0

Related Questions