From 4bf60b30a0c53a36246076e3de8ce8a3ff8bf250 Mon Sep 17 00:00:00 2001 From: Blaize M Kaye Date: Mon, 11 Dec 2023 11:07:08 +1300 Subject: [PATCH] Further factoring --- internal/service/db.go | 24 ++++++++++++++++++++++++ internal/service/service.go | 15 +++------------ 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/internal/service/db.go b/internal/service/db.go index 2723020..9ce05b9 100644 --- a/internal/service/db.go +++ b/internal/service/db.go @@ -1,6 +1,7 @@ package service import ( + "errors" "github.com/uselagoon/lagoon/services/insights-handler/internal/lagoonclient" "gorm.io/gorm" ) @@ -8,3 +9,26 @@ import ( func CreateFacts(db *gorm.DB, facts *[]lagoonclient.Fact) error { return db.Create(facts).Error } + +type DeleteFactsOptions struct { +} + +func DeleteFacts(db *gorm.DB, environmentId int, source string) (int64, error) { + + if environmentId == 0 { + return 0, errors.New("EnvironmentId cannot be 0") + } + + conditions := map[string]interface{}{ + "environment": environmentId, + } + + if source != "" { + conditions["source"] = source + } + + result := db.Where(conditions).Delete(&lagoonclient.Fact{}) + + return result.RowsAffected, result.Error + +} diff --git a/internal/service/service.go b/internal/service/service.go index 4fde676..969a1ea 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -77,24 +77,15 @@ func DeleteFactsByEnvironmentEndpoint(c *gin.Context) { return } - // Build conditions for deletion based on optional parameters - conditions := map[string]interface{}{ - "environment": environmentID, - } - - if source != "" { - conditions["source"] = source - } - // Delete facts based on conditions - result := gormDB.Where(conditions).Delete(&lagoonclient.Fact{}) - if result.Error != nil { + rowsAffected, err := DeleteFacts(gormDB, environmentID, source) //gormDB.Where(conditions).Delete(&lagoonclient.Fact{}) + if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete facts from the database"}) return } // Check if any records were deleted - if result.RowsAffected == 0 { + if rowsAffected == 0 { c.JSON(http.StatusNotFound, gin.H{"message": "No matching facts found for deletion"}) return }