package dbhandling
-import "net/http"
+import (
+ "encoding/json"
+ "net/http"
+)
-/** TODO
+/**
* Get all songs, and all their assosciated information from the db
**/
func (dbw *DBWrapper) SongsGet(w http.ResponseWriter, r *http.Request) {
// Here we should return an entire list of songs
+ keys, err := dbw.RedisDb.Keys(dbw.ctx, "song:*").Result()
+ if err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ key_count := len(keys)
+
+ allSongs := make([]DBSong, key_count)
+ for i, k := range keys {
+ intf, err := dbw.RedisDb.HMGet(dbw.ctx, k, "artistName", "trackName", "trackViewUrl", "previewUrl", "artworkUrl60", "artworkUrl100", "displayArtistNames", "displayTrackName").Result()
+ if err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+ song := DBSong{
+ Key: k,
+ ArtistName: intf[0].(string),
+ TrackName: intf[1].(string),
+ TrackViewURL: intf[2].(string),
+ PreviewURL: intf[3].(string),
+ ArtworkURL60: intf[4].(string),
+ ArtworkURL100: intf[5].(string),
+ DisplayArtistNames: intf[6].(string),
+ DisplayTrackName: intf[7].(string),
+ }
+ allSongs[i] = song
+ }
+
+ b, err := json.Marshal(allSongs)
+ if err != nil {
+ w.WriteHeader(http.StatusInternalServerError)
+ return
+ }
+
+ w.Write(b)
+
}
/** TODO
package dbhandling_test
-import "testing"
+import (
+ "encoding/json"
+ "net/http/httptest"
+ "songmanager/pkg/dbhandling"
+ "testing"
+)
+
+type EmptyReader struct {}
+
+func (r *EmptyReader) Read(p []byte) (int, error) {
+ return 0, nil
+}
+
func TestGetSongs(t *testing.T) {
// setup some fake requests
+ r := httptest.NewRequest("GET", "/api/songs/get", &EmptyReader{})
+ wrapper := dbhandling.NewDbWrapper("localhost:6379", "./testing/songs")
// subtests
+ t.Run("SongsGet1", func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ wrapper.SongsGet(recorder, r)
+
+ l := make([]dbhandling.DBSong, 10)
+ err := json.Unmarshal(recorder.Body.Bytes(), &l)
+ if err != nil {
+ t.Error("Failed unmarshling JSON body from GetSongs Response")
+ }
- // get answers to those requests
+ if len(l) != 10 {
+ t.Error("Returned JSON is of wrong length")
+ }
+ })
}