Repository navigation
Expand file tree
/
Copy pathCityController.java
More file actions
69 lines (55 loc) · 2.37 KB
/
Copy pathCityController.java
File metadata and controls
69 lines (55 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.citysounds.controllers;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.citysounds.models.City;
import com.citysounds.repository.CityRepository;
import com.citysounds.services.SpotifyService;
// This is the primary RESTAPI for citySounds
/*
REPOSITORY -> cityRepository
SERVICE -> SpotifyService
ENDPOINTS ->
/api/cities: Calls getAllCities()
- returns all city objects for initiazation of the cites on the globe
/api/cities/{id}: calls getCityviaID(parameter: id)
- When City is clicked on -> return city object
/api/cities{id}/music: calls GetMusicForCity(parameter: id)
- Fetches the music track using the spotify Service; else, return an error
*/
@RestController
public class CityController {
private final CityRepository cityRepository;
private final SpotifyService spotifyService;
public CityController(CityRepository cityRepository, SpotifyService spotifyService){
this.cityRepository = cityRepository;
this.spotifyService = spotifyService;
}
// This recieves a request from app.js and returns all of the city objects. for initializatiuon of the globe
@GetMapping("/api/cities")
public List<City> getAllCities(){
return cityRepository.findAll();
}
// This recieves a fetch from when you click on a city andi t will return that city object
@GetMapping("/api/cities/{id}")
public City getCityviaID(@PathVariable Long id) {
return cityRepository.findById(id).orElse(null);
}
// This fetches the music for the city once it is clicked on
@GetMapping("/api/cities/{id}/music")
public ResponseEntity<String> GetMusicForCity(@PathVariable Long id){
City city = cityRepository.findById(id).orElse(null);
if (city == null) {
return ResponseEntity.notFound().build();
}
try {
String trackId = spotifyService.getCuratedCityTrack(city.getId(), city.getCountryCode());
return ResponseEntity.ok(trackId != null && !trackId.isEmpty() ? trackId : "");
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.internalServerError().body("");
}
}
}