Backend Low Level Design 4
About Lesson

Create a logout method in the UserController. This method will return ResponseEntity and take a request parameter as token. Next, call a logout method from the UserService, which we’ll create next. This method will take the token as a parameter.

@PostMapping(“/logout”)
public ResponseEntity<Void> logout(@RequestParam(“token”) String token){
   userService.logout(token);
   return new ResponseEntity<>(HttpStatus.OK);
}
Next, within the UserService, establish a method named Logout. First, call the findByValueAndIsDeletedEquals method from tokenRepository. Check if it is empty; if so, return. Otherwise, set deleted to true and save it in the repository.
public void logout(String token) {
    Optional<Token> tokenOptional
            = tokenRepository.findByValueAndIsDeletedEquals(token, false);

    if (tokenOptional.isEmpty()) {
        // throw an exception saying token is not present or already deleted.
        return ;
    }

    Token updatedToken = tokenOptional.get();
    updatedToken.setDeleted(true);
    tokenRepository.save(updatedToken);
 }
 

Next, Write a method findByValueAndDeletedEquals in TokenRepository.

@Repository
public interface TokenRepository extends JpaRepository<Token, Long> {
   Optional<Token> findByValueAndIsDeletedEquals(String token, boolean isDeleted);
}

Next now open postman

Now, open Postman and select the method as POST. Use the URL http://localhost:8080/logout?token=tokenvalue.

Click on “Send“. If this works, it will not return any response but you can check in the database. Select token table ad check isDeleted column is true

© GeekySanjay