From eb51bdbfef8c2aacf0fdfde279a40de7f74c8d86 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Mon, 18 Mar 2024 21:27:24 -0400 Subject: clean up, add better error handling --- api/internal/controllers/stats.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) (limited to 'api/internal/controllers/stats.go') diff --git a/api/internal/controllers/stats.go b/api/internal/controllers/stats.go index 2234787..889b923 100644 --- a/api/internal/controllers/stats.go +++ b/api/internal/controllers/stats.go @@ -2,10 +2,11 @@ package controllers import ( "database/sql" - "github.com/gin-gonic/gin" "net/http" "water/api/internal/database" "water/api/internal/models" + + "github.com/gin-gonic/gin" ) // TODO: add comments to all exported members of package. @@ -13,7 +14,11 @@ import ( // GetAllStatistics connects to the database and queries for all statistics in the database. // If none have been found it will return an error, otherwise a 200 code is sent along with the list of statistics. func GetAllStatistics(c *gin.Context) { - db := database.EstablishDBConnection() + db, err := database.EstablishDBConnection() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } defer func(db *sql.DB) { err := db.Close() if err != nil { @@ -59,7 +64,11 @@ func PostNewStatistic(c *gin.Context) { return } - db := database.EstablishDBConnection() + db, err := database.EstablishDBConnection() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } defer func(db *sql.DB) { err := db.Close() if err != nil { @@ -83,7 +92,11 @@ func PostNewStatistic(c *gin.Context) { } func GetWeeklyStatistics(c *gin.Context) { - db := database.EstablishDBConnection() + db, err := database.EstablishDBConnection() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } defer func(db *sql.DB) { err := db.Close() if err != nil { @@ -118,7 +131,11 @@ func GetWeeklyStatistics(c *gin.Context) { } func GetDailyUserStatistics(c *gin.Context) { - db := database.EstablishDBConnection() + db, err := database.EstablishDBConnection() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } defer func(db *sql.DB) { err := db.Close() if err != nil { -- cgit v1.1