Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 502
Adron Avatar asked Aug 14 '14 18:08

Adron


People also ask

Should I use Joi or express validator?

Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.

What is Joi validation?

Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.


2 Answers

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()
});
like image 166
Gergo Erdosi Avatar answered Sep 20 '22 16:09

Gergo Erdosi


You can use the "allowUnknown" parameter:

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

}

like image 27
Jaraxal Avatar answered Sep 19 '22 16:09

Jaraxal