Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does validation check go in repository pattern?

Lets say I have an entity called User which has many Posts. My service looks like this for the deletion of a post:

void DeletePost(int postId, int userId);

Where does my validation code go? (ensure that the user has permission to delete). Should I do this in the repository with 1 database call? Or should I do this check in the Service layer where I make 2 calls:

  1. Get the user by userId.
  2. Call delete after validation has been done on the user.

I will have 2 repositories, 1 for the user and 1 for the post, each looking like this:

// From the PostRepository.
void Delete(int postId); //May have to add a userId param if I do validation in repository
//From the UserRepository.
User GetUser(int userId);
like image 882
Shawn Mclean Avatar asked Jan 04 '11 21:01

Shawn Mclean


People also ask

What are validation checks in a database?

Validation is an automatic computer check to ensure that the data entered is sensible and reasonable. It does not check the accuracy of data.

Should I validate controller or service?

As a general rule of thumb, I would say that business logic of this sort should be in the service. Controllers should be light-weight and pass on requests. Further, there may be other clients of your service, not just controllers, so this allows you to keep validation in one place.

What is type check in validation?

A type check will ensure that the correct type of data is entered into that field. For example, in a clothes shop, dress sizes may range from 8 to 18. A number data type would be a suitable choice for this data.


2 Answers

That's a business rule so I wouldn't place it on the data access layer (Repository). I'd say the best place is the service layer.

like image 112
Claudio Redi Avatar answered Sep 20 '22 03:09

Claudio Redi


I think some validation should happen before you get to the repository i.e. in the domain model / business layer.

You may opt to validate in depth and perform validation also in the repository layer; this may or may not be a good idea depending on what the validation is for; if the validation is domain specific then it strikes me that the validation should be in the domain model. On the other hand, if the validation is less domain specific and more general in its nature, then having it in the repository / data access layer means that the validation can be reused across other projects in which the data access layer is reused.

like image 39
Russ Cam Avatar answered Sep 22 '22 03:09

Russ Cam