Explorar el Código

fix: don't throw an unhandled error when song ID does not exist

Fela Maslen hace 5 años
padre
commit
82c37cffdb

+ 20 - 7
gmus-backend/pkg/repository/player.go

@@ -1,9 +1,23 @@
 package repository
 
-import "github.com/jmoiron/sqlx"
+import (
+	"database/sql"
+
+	"github.com/jmoiron/sqlx"
+)
+
+func getSongIdOrZero(db *sqlx.DB, query string, songId int64) (assocSongId int64, err error) {
+	err = db.QueryRowx(query, songId).Scan(&assocSongId)
+	if err != nil && err == sql.ErrNoRows {
+		err = nil
+		assocSongId = 0
+	}
+	return
+}
 
 func GetNextSongId(db *sqlx.DB, prevSongId int64) (nextSongId int64, err error) {
-	err = db.QueryRowx(
+	nextSongId, err = getSongIdOrZero(
+		db,
 		`
     select coalesce(id_next, 0) as id from (
       select
@@ -66,13 +80,13 @@ func GetNextSongId(db *sqlx.DB, prevSongId int64) (nextSongId int64, err error)
     ) result
     `,
 		prevSongId,
-	).Scan(&nextSongId)
-
+	)
 	return
 }
 
 func GetPrevSongId(db *sqlx.DB, nextSongId int64) (prevSongId int64, err error) {
-	err = db.QueryRowx(
+	prevSongId, err = getSongIdOrZero(
+		db,
 		`
     select coalesce(id_prev, 0) as id from (
       select
@@ -135,7 +149,6 @@ func GetPrevSongId(db *sqlx.DB, nextSongId int64) (prevSongId int64, err error)
     ) result
     `,
 		nextSongId,
-	).Scan(&prevSongId)
-
+	)
 	return
 }

+ 18 - 0
gmus-backend/pkg/repository/player_test.go

@@ -84,6 +84,15 @@ var _ = Describe("Player repository", func() {
 				Expect(id).To(Equal(int64(0)))
 			})
 		})
+
+		Context("when the ID does not exist", func() {
+			It("should return nil", func() {
+				id, err := repository.GetNextSongId(db, 10000000)
+
+				Expect(err).To(BeNil())
+				Expect(id).To(BeZero())
+			})
+		})
 	})
 
 	Describe("GetPrevSongId", func() {
@@ -114,5 +123,14 @@ var _ = Describe("Player repository", func() {
 				Expect(id).To(Equal(int64(0)))
 			})
 		})
+
+		Context("when the ID does not exist", func() {
+			It("should return nil", func() {
+				id, err := repository.GetPrevSongId(db, 10000000)
+
+				Expect(err).To(BeNil())
+				Expect(id).To(BeZero())
+			})
+		})
 	})
 })