Skip to content

Commit

Permalink
refactor: Refactor event model and service
Browse files Browse the repository at this point in the history
  • Loading branch information
peterxcli committed Feb 28, 2024
1 parent 798ad3d commit 26a4b92
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 4 deletions.
54 changes: 53 additions & 1 deletion pkg/model/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package model
import (
"context"
"encoding/json"
"reflect"
"time"

"github.com/google/uuid"
"gorm.io/gorm"
"time"
)

var (
Expand Down Expand Up @@ -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
Expand Down
16 changes: 13 additions & 3 deletions pkg/service/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package service
import (
"bikefest/pkg/model"
"context"
"errors"
"time"

"github.com/redis/go-redis/v9"
Expand All @@ -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
Expand Down

0 comments on commit 26a4b92

Please sign in to comment.