Skip to content

Commit

Permalink
fix: pet bool field update with map
Browse files Browse the repository at this point in the history
  • Loading branch information
bookpanda committed Feb 17, 2024
1 parent 88e0c4a commit ea597e9
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/app/model/pet/pet.model.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type Pet struct {
Caption string `json:"caption" gorm:"mediumtext"`
Status pet.Status `json:"status" gorm:"mediumtext" example:"findhome"`
IsSterile bool `json:"is_sterile"`
IsVaccinated bool `json:"is_vaccine"`
IsVaccinated bool `json:"is_vaccinated"`
IsVisible bool `json:"is_visible"`
Origin string `json:"origin" gorm:"tinytext"`
Address string `json:"address" gorm:"tinytext"`
Expand Down
4 changes: 3 additions & 1 deletion src/app/repository/pet/pet.repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"

"github.com/isd-sgcu/johnjud-backend/src/app/model/pet"
petUtils "github.com/isd-sgcu/johnjud-backend/src/app/utils/pet"
"gorm.io/gorm"
)

Expand All @@ -28,7 +29,8 @@ func (r *Repository) Create(in *pet.Pet) error {
}

func (r *Repository) Update(id string, result *pet.Pet) error {
return r.db.Where(id, "id = ?", id).Updates(&result).First(&result, "id = ?", id).Error
updateMap := petUtils.UpdateMap(result)
return r.db.Model(&result).Updates(updateMap).First(&result, "id = ?", id).Error
}

func (r *Repository) Delete(id string) error {
Expand Down
18 changes: 18 additions & 0 deletions src/app/utils/pet/pet.utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package pet
import (
"errors"
"math"
"reflect"
"strings"
"time"

Expand Down Expand Up @@ -181,6 +182,23 @@ func ExtractImageIDs(in []*imageProto.Image) []string {
return result
}

func UpdateMap(in *pet.Pet) map[string]interface{} {
updateMap := make(map[string]interface{})
t := reflect.TypeOf(*in)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
typeName := field.Type.Name()
value := reflect.ValueOf(*in).Field(i).Interface()
if typeName == "string" && value != "" {
updateMap[field.Name] = value
}
if typeName == "bool" {
updateMap[field.Name] = value
}
}
return updateMap
}

func parseDate(dateStr string) (time.Time, error) {
parsedTime, err := time.Parse(time.RFC3339, dateStr)
if err != nil {
Expand Down

0 comments on commit ea597e9

Please sign in to comment.