#191 Code Review of a Users and Cards Controller

Companies:
Sovcombank
Themes:
SpringSpring BootCode Review

Perform a code review:

@Controller
@RequestMapping(path = "/users")
public class MainController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CardRepository cardRepository;

    @RequestMapping(path = "/getUser", method = RequestMethod.GET)
    public User getUser(String username) {

        User user = restTemplate.getForObject("/loadUser/{username}", User.class, username);

        Optional<User> dbUser = userRepository.findAll()
            .stream()
            .filter(u -> u.getUsername().equals(username))
            .findAny();

        if (dbUser.isEmpty()) {
            return userRepository.save(user);
        }

        return dbUser.get();
    }

    @RequestMapping(path = "/getCards", method = RequestMethod.GET)
    public List<Card> getCards(String username) {

        Optional<User> user = userRepository.findAll()
            .stream()
            .filter(u -> u.getUsername().equals(username))
            .findAny();

        if (user.isPresent()) {
            return user.get().getCards();
        }

        return null;
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in