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

Viewed 7355

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?

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(),
 });

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)

Related