package grpcapi import ( "encoding/json" "fmt" "git.coopgo.io/coopgo-platform/agenda/storage" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" ) func (e Event) ToStorageType() storage.Event { event := storage.Event{ ID: e.Id, Namespace: e.Namespace, Owners: e.Owners, RestrictedTo: e.RestrictedTo, Type: e.Type, Name: e.Name, Description: e.Description, Startdate: e.Startdate.AsTime(), Enddate: e.Enddate.AsTime(), Starttime: e.Starttime, Endtime: e.Endtime, Allday: e.Allday, MaxSubscribers: e.MaxSubscribers, Subscriptions: []storage.Subscription{}, Data: map[string]any{}, } for _, v := range e.Subscriptions { event.Subscriptions = append(event.Subscriptions, v.ToStorageType()) } for k, d := range e.Data.GetFields() { jsondata, err := protojson.Marshal(d) if err != nil { fmt.Println(err) break } var data any json.Unmarshal(jsondata, &data) event.Data[k] = data } return event } func (s Subscription) ToStorageType() storage.Subscription { subscription := storage.Subscription{ Subscriber: s.Subscriber, Tags: s.Tags, Data: s.Data.AsMap(), CreatedAt: s.CreatedAt.AsTime(), } return subscription } func EventFromStorageType(event *storage.Event) (*Event, error) { d, err := sanitizeData(event.Data) if err != nil { return nil, err } data, err := structpb.NewStruct(d) if err != nil { fmt.Println(err) return nil, err } subscriptions := []*Subscription{} for _, v := range event.Subscriptions { sub, _ := SubscriptionFromStorageType(v) subscriptions = append(subscriptions, sub) } return &Event{ Id: event.ID, Namespace: event.Namespace, Type: event.Type, Owners: event.Owners, RestrictedTo: event.RestrictedTo, Name: event.Name, Description: event.Description, Startdate: timestamppb.New(event.Startdate), Enddate: timestamppb.New(event.Enddate), Starttime: event.Starttime, Endtime: event.Endtime, Allday: event.Allday, MaxSubscribers: event.MaxSubscribers, Subscriptions: subscriptions, Data: data, }, nil } func SubscriptionFromStorageType(s storage.Subscription) (*Subscription, error) { d, err := sanitizeData(s.Data) if err != nil { return nil, err } data, err := structpb.NewStruct(d) if err != nil { fmt.Println(err) return nil, err } subscription := Subscription{ Subscriber: s.Subscriber, Tags: s.Tags, Data: data, CreatedAt: timestamppb.New(s.CreatedAt), } return &subscription, nil } func sanitizeData(data map[string]any) (d map[string]any, err error) { j, err := json.Marshal(data) if err != nil { return nil, err } if err = json.Unmarshal(j, &d); err != nil { return nil, err } return d, nil }