fleets/grpcapi/vehicles.go

88 lines
1.7 KiB
Go

package grpcapi
import (
"encoding/json"
"fmt"
"git.coopgo.io/coopgo-platform/fleets/storage"
"google.golang.org/protobuf/encoding/protojson"
structpb "google.golang.org/protobuf/types/known/structpb"
)
func (v Vehicle) ToStorageType() storage.Vehicle {
vehicle := storage.Vehicle{
ID: v.Id,
Namespace: v.Namespace,
Type: v.Type,
Administrators: v.Administrators,
Data: map[string]any{},
}
for k, d := range v.Data.GetFields() {
jsondata, err := protojson.Marshal(d)
if err != nil {
fmt.Println(err)
break
}
var data any
json.Unmarshal(jsondata, &data)
vehicle.Data[k] = data
}
bookings := []storage.Booking{}
for _, b := range v.Bookings {
bookings = append(bookings, b.ToStorageType())
}
vehicle.Bookings = bookings
return vehicle
}
func VehicleFromStorageType(vehicle *storage.Vehicle) (*Vehicle, error) {
d, err := sanitizeData(vehicle.Data)
if err != nil {
return nil, err
}
data, err := structpb.NewStruct(d)
if err != nil {
fmt.Println(err)
return nil, err
}
bookings := []*Booking{}
for _, b := range vehicle.Bookings {
nb, err := BookingFromStorageType(&b)
if err != nil {
fmt.Println(err)
return nil, err
}
bookings = append(bookings, nb)
}
return &Vehicle{
Id: vehicle.ID,
Namespace: vehicle.Namespace,
Type: vehicle.Type,
Administrators: vehicle.Administrators,
Data: data,
Bookings: bookings,
}, 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
}