Search code examples
inputdynamickeyruntimejoi

How can I use Dynamic key in Joi


I am a beginner in Joi.

I want to make the following 'folderContent' a dynamic value, it can be 'onlySubject' or 'otherDetails' or whatever I will give as input during runtime.

Details: In the schema('bodySchema') , there is a object ('superObject')under which there is another object ('folderContent'), within that there is a string ('subject')

const bodySchema=Joi.object({
superObject: Joi.object()
    .when('grade', {
      is: 'class6',
      then: {
        folderContent: Joi.object({
            subject: Joi.string(),
          }),
      },
    })
});

So the input looks like the following where instead of 'folderContent' I want to give dynamic key value

"superObject": {
        "folderContent": {
            "subject": "Geography"
        }
    }

I have tried the followings, but did not work: 1)superObject: Joi.object() .when('grade', { is: 'class6', then: {

    folderContent: Joi.object()
      .keys({
        subject: Joi.string(),
      })
      .unknown(true),
    
  },
})

2)superObject: Joi.object() .when('grade', { is: 'class6', then: {

    folderContent: Joi.object()
      ({
        subject: Joi.string(),
      })
      .unknown(true),
    
  },
})

Error is coming when I give input as 'onlySubject' for 'folderContent' { "success": false, "exception": "InvalidBodyParameters", "message": ""superObject.onlySubject" is not allowed", "stack": "ValidationError: "superObject.onlySubject" is not allowed" }


Solution

  • Got it, the following is working fine. With the help of your pattern it worked, thank you so much.

    superObject
    : Joi.object()
    
        .when(‘grade’, {
          is: ‘class6’,
          then: Joi.object().pattern(
            Joi.string(),
            Joi.object({
              subject: Joi.string(),
            })
          ),
        })
        .when(‘grade’, {
          is: ‘class5’,
          then: Joi.object().pattern(
            Joi.string(),
            Joi.object({
              subject: Joi.string(),
              Pattern: Joi.string(),
            })
          ),
        }),