jeudi 15 décembre 2016

API controller and underlying service - responsibility for arguments validation

Maybe it’s trivial situation but it’s confusing for me and I need some clarification how to deal with it in the right way.

To make it simple the model is as fallow:

User * - * Project

(User is assigned to many projects and project has many users assigned to).

I created rest controller for assigning and dismissing users from specific project:

…\Api\v1\Projects\{projectId}\users\{userId}

Two http action are allowed:

  • POST action to assign existing user to project and
  • DELETE to dismiss user from project. (Not sure if it’s right solution but it works for me).

API Controller use service layer to perform these operation. Service interface is as fallow:

void projectService.assignUser(int projectId, int userId)
void projectService.dismissUser(int projectId, int userId)

Service use dbContext to perform these operation.

Question 1: Which element should be responsible for checking if projectId and userId are correct? IMHO it’s better to put this logic in service layer as it can be reuse.

Question 2: What these method should return in case the projectId and userid are incorrect (for instance: project/user does not exist or is not allowed to be assigned)?

My first thought was to return null value but I think it’s not very meaningful. Mainly because the similar methods in service returns null if enitiyId is incorrect. For instance: projectService.getProject(projectId) – return null if project doesn’t exists

The second though was to return bool. False is at least one of argument is incorrect

The third thought was to throw ArgumentException with message. It’s seems to be good but it makes api controller to catch the exception.

Aucun commentaire:

Enregistrer un commentaire