Reputation: 1771
I'm using symfony with API PLATFORM to create a contacts share system :
One User can share one or many contacts to one or many other users.
I created ContactShare entity :
/**
* @ApiResource()
* @ORM\Entity(repositoryClass=ContactShareRepository::class)
*/
class ContactShare
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity=Contact::class, mappedBy="contactsToShare")
*/
private $contacts;
/**
* @ORM\ManyToOne(targetEntity=AppUser::class, inversedBy="shareContactsOwner")
*/
private $sender;
/**
* @ORM\OneToMany(targetEntity=AppUser::class, mappedBy="shareContactsReceivers")
*/
private $receivers;
...
...
}
When i tested with postman i can post a new share :
My question is :
How to add constraints or validators to prevent the POST method of contact share if we
share the same contacts to the same user, and Prevent POST method if we send the same
contact to a duplicated user ?
Upvotes: 0
Views: 641
Reputation: 29912
You can create a custom validator and call valid
as shown here.
If validation returns one (or more) error, you should return some kind of response with proper HTTP status code (4xx?).
Moreover, if this validation should be performed only for this API call (I think this is a domain requirement, so it should be always applyed, but it's only a guess of mine) you can take advantage of validation groups.
UPDATE: API Platform seems to take care of this on your behalf, so you don't need to call explicitly valid
Upvotes: 1