Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating unique key pairs in a nested object with Joi and nodeJS

I have the following JSON structure:

{
  key1: "value1",
  key2: "value2",
  transactions: [
    {
      receiverId: '12341',
      senderId: '51634',
      someOtherKey: 'value'
    },
    {
      receiverId: '97561',
      senderId: '46510',
      someOtherKey: 'value'
    }
  ]
}

I'm trying to write some Joi code to validate that each object in the transactions array is unique i.e. a combination of receiverId and senderId is only ever present once. There can be a variable number of elements in the transactions array but there will always be at least 1. Any thoughts?

like image 302
Akshay Bhimrajka Avatar asked Nov 10 '18 20:11

Akshay Bhimrajka


2 Answers

You can use array.unique

const array_uniq_schema = Joi.array().unique((a, b) => a.receiverId === b.receiverId && a.senderId === b.senderId);

So for the whole object the schema would be (assuming all properties are required):

 const schema = Joi.object({
    key1: Joi.string().required(),
    key2: Joi.string().required(),
    transactions: array_uniq_schema.required(),
 });
like image 77
Christian Avatar answered Sep 17 '22 23:09

Christian


an easy way :

const schema = Joi.object({
    transactions: Joi.array()
        .unique('receiverId')
        .unique('senderId')
        .required(),
});

This way it returns an error for each field (one error for ReceivedId and another one for senderId)

like image 36
Muslim Omar Avatar answered Sep 21 '22 23:09

Muslim Omar