Skip to content

Commit

Permalink
Further factoring
Browse files Browse the repository at this point in the history
  • Loading branch information
bomoko committed Dec 10, 2023
1 parent e98733a commit 4bf60b3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
24 changes: 24 additions & 0 deletions internal/service/db.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
package service

import (
"errors"
"github.com/uselagoon/lagoon/services/insights-handler/internal/lagoonclient"
"gorm.io/gorm"
)

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

}
15 changes: 3 additions & 12 deletions internal/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 4bf60b3

Please sign in to comment.