10

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?

frederj
  • 1,483
  • 9
  • 20

2 Answers2

13

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(),
 });
Christian
  • 7,433
  • 4
  • 36
  • 61
8

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)

Muslem Omar
  • 1,021
  • 12
  • 12