简体   繁体   中英

When using Joi with Hapi, how does one setup a require on one key but allow any and all other keys?

I'm trying to write a Joi validation for a JSON object coming into a Hapi handler. So far the code looks like this:

server.route({
    method: 'POST',
    path: '/converge',
    handler: function (request, reply) {
        consociator.consociate(request.payload)
            .then (function (result) {
                reply (200, result);
            });
    },
    config: {
        validate: {
            payload: {
                value: Joi.object().required().keys({ knownid: Joi.object() })
            } 
        }
    }
});

You can see the Joi object validation so far in the config: validate: code section above. The JSON coming in looks like this.

"key": '06e5140d-fa4e-4758-8d9d-e707bd19880d-testA',
"value": {
    "ids_lot_args": {
        "this_id": "stuff",
        "otherThign": "more data"
    },
    "peripheral_data": 'Sample peripheral data of any sort'
}

In this JSON above the key and value at the root of the object are required, and the section called ids_lot_args is required. The section that starts with peripheral_data could be there or not, or could be any other JSON payload. It doesn't matter, only key and value at the root level and ids_lot_args inside the value are required.

So far, I'm stumbling through trying to get the Joi validation to work. Any ideas on how this should be setup? The code repo for Joi is located at https://github.com/hapijs/joi if one wants to check it out. I've been trying the allow all functions on objects to no avail so far.

You just need to call the unknown() function on the value object:

var schema = Joi.object({
  key: Joi.string().required(),
  value: Joi.object({
    ids_lot_args: Joi.object().required()
  }).unknown().required()
});

You can use the "allowUnknown" parameter:

validate : {
  options : {
    allowUnknown: true
  },
  headers : {
  ...
  },
  params : {
  ...
  },
  payload : {
  ...
  }
}

}

Try using Joi.any()

server.route({
    method: 'POST',
    path: '/converge',
    handler: function (request, reply) {
        consociator.consociate(request.payload)
            .then (function (result) {
                reply (200, result);
            });
    },
    config: {
        validate: {
            payload: {
                key: Joi.string().required(),
                value: Joi.object({
                  ids_lot_args: Joi.object().required(),
                  peripheral_data: Joi.any()
                })
            } 
        }
    }});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM