На каком уровне лучше использовать RestTemplate?
У меня есть web-приложение, которое взаимодействует с Spotify API. Для запросов я использую клас RestTemplate. Приведу пример, мне нужной найти топ треков пользователя, я делаю соответствующий запрос в сервисе: TopTrackService:
@Service
public class TopTrackService {
private final AuthService authService;
private final RestTemplate restTemplate;
private final ObjectMapper mapper;
@Autowired
public TopTrackService(AuthService authService, RestTemplate restTemplate, ObjectMapper mapper) {
this.authService = authService;
this.restTemplate = restTemplate;
this.mapper = mapper;
}
private final String url = "https://api.spotify.com/v1/me/top/tracks?limit=10&time_range=";
public void findTopTracks(String term, Model model) throws JsonProcessingException {
JsonNode currentUserTopTracksJson = mapper.readTree(restTemplate.exchange( url + term, HttpMethod.GET, authService.useToken(), String.class).getBody());
//Top track card
model.addAttribute("tracks", currentUserTopTracksJson.get("items"));
}
}
А потом внедряю его в контроллер и вызываю там метод:
MainController:
@Controller
public class MainController {
private final AuthService authService;
private final TopTrackService topTrackService;
private final TopArtistService topArtistService;
private final UserService userService;
public final RestTemplate restTemplate;
@Autowired
public MainController(AuthService authService, TopTrackService topTrackService, TopArtistService topArtistService, UserService userService, RestTemplate restTemplate) {
this.authService = authService;
this.topTrackService = topTrackService;
this.topArtistService = topArtistService;
this.userService = userService;
this.restTemplate = restTemplate;
}
@GetMapping("/profile")
public String myProfile(@RequestParam(value = "time_range",defaultValue = "short_term") String time_range, Model model) throws JsonProcessingException, UnauthorizedUserException {
//Top track Card
topTrackService.findTopTracks(time_range,model);
return "profile";
}
}
Не могу понять что считаеться хорошим стилем: делать Rest запросы в контроллере или же в сервисе?