Skip to content
Advertisement

Where should I check if username already exist in rest api?

I am creating a rest application using Spring Boot. I’ve got three logical layers: controller, service, and repository. Where should I check if the given username and similar values already exist in the database?

In the controller layer, I check user input (length, size, etc.) Can I also check username existence here? For instance:

if(this.userService.existUserByUsername(request.getUsername()))
        throw new ResponseStatusException(
                HttpStatus.CONFLICT, "User with given username already exists");

Can I check it in the service layer by invoking the registry method (existByUsername) and throwing a custom error, then caught in the controller?

public void addUser(SignUpRequestDto signUpRequestDto){
    
    if(this.userRepository.existsByUsername(signUpRequestDto.getUsername()))
        throw new UserAlreadyExistException("User with given uusernamealready exist");
    else
        this.userRepository.save(this.convertSignUpRequestDtoToEntity(signUpRequestDto));
}

Or maybe I should rely on hibernate annotations on entities and handle these exceptions?

@NotNull
@Column(name = "username", unique = true)
private String username;

I really appreciate all feedback from you.

Advertisement

Answer

Where should I check if the given username and similar values already exist in the database?

Probably in the same logical layer that the rest of your business logic lives. Service layer?

In the controller layer, I check user input (length, size, etc.) Can I also check username existence here?

You can, of course. It’s probably not a good idea; parsing inputs to make sure that they conform to a schema that you understand is a boundary concern. Using the inputs that you understand is a domain concern.

Can I check it in the service layer by invoking the registry method (existByUsername) and throwing a custom error, then caught in the controller?

You can – you may get some push back during code review about whether an exception is the right implementation mechanism to handle that. There are alternative approaches, and trade offs between them, and contexts (throwing exceptions within a layer vs throwing exceptions between layers).

Advertisement