From 26a4b9212a9aa0dc60d7bc98b88825065118c39e Mon Sep 17 00:00:00 2001 From: peterxcli Date: Wed, 28 Feb 2024 17:08:23 +0800 Subject: [PATCH] refactor: Refactor event model and service --- pkg/model/event.go | 54 +++++++++++++++++++++++++++++++++++++++++++- pkg/service/event.go | 16 ++++++++++--- 2 files changed, 66 insertions(+), 4 deletions(-) diff --git a/pkg/model/event.go b/pkg/model/event.go index 9de74a2..b549338 100644 --- a/pkg/model/event.go +++ b/pkg/model/event.go @@ -3,9 +3,11 @@ package model import ( "context" "encoding/json" + "reflect" + "time" + "github.com/google/uuid" "gorm.io/gorm" - "time" ) var ( @@ -67,6 +69,56 @@ type EventDetails struct { Link string `json:"link"` } +func (e *EventDetails) UnmarshalJSON(data []byte) error { + type Alias EventDetails + aux := &struct { + *Alias + }{ + Alias: (*Alias)(e), + } + + if err := json.Unmarshal(data, &aux); err != nil { + return err + } + + v := reflect.ValueOf(e).Elem() + for i := 0; i < v.NumField(); i++ { + field := v.Field(i) + fieldType := v.Type().Field(i) + + if fieldType.Type.Kind() == reflect.String && field.String() == "" { + switch fieldType.Name { + case "ID": + field.SetString("id") + case "Name": + field.SetString("name") + case "Activity": + field.SetString("activity") + case "Project": + field.SetString("project") + case "Description": + field.SetString("description") + case "Date": + defaultTime, _ := time.Parse("2006/01/02 ", "2025/01/01") + field.SetString(defaultTime.Format("2006/01/02")) + case "StartTime": + field.SetString("00:00") + case "EndTime": + field.SetString("00:00") + case "Location": + field.SetString("location") + case "Host": + field.SetString("host") + case "Link": + field.SetString("https://google.com") + default: + } + } + } + + return nil +} + func CaculateEventID(event *Event) (string, error) { eventMap := make(map[string]interface{}) eventMap["event_time_start"] = event.EventTimeStart diff --git a/pkg/service/event.go b/pkg/service/event.go index 136f101..6a6506e 100644 --- a/pkg/service/event.go +++ b/pkg/service/event.go @@ -3,6 +3,7 @@ package service import ( "bikefest/pkg/model" "context" + "errors" "time" "github.com/redis/go-redis/v9" @@ -17,10 +18,19 @@ type EventServiceImpl struct { func (es *EventServiceImpl) StoreAll(ctx context.Context, events []*model.Event) error { txn := es.db.WithContext(ctx).Begin() for _, event := range events { - err := txn.WithContext(ctx).Create(event).Error + // check if the event already exists in the database, if so, update it, otherwise, create a new one + var existingEvent model.Event + err := txn.Where(&model.Event{ID: event.ID}).First(&existingEvent).Error if err != nil { - txn.Rollback() - return err + if !errors.Is(err, gorm.ErrRecordNotFound) { + txn.Rollback() + return err + } + err = txn.Create(event).Error + if err != nil { + txn.Rollback() + return err + } } } err := txn.Commit().Error