73 lines
1.5 KiB
Go
73 lines
1.5 KiB
Go
package cart
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
messages "git.tornberg.me/go-cart-actor/pkg/messages"
|
|
)
|
|
|
|
func UpsertSubscriptionDetails(g *CartGrain, m *messages.UpsertSubscriptionDetails) error {
|
|
if m == nil {
|
|
return nil
|
|
}
|
|
metaBytes := m.Data.GetValue()
|
|
|
|
// Create new subscription details when Id is nil.
|
|
if m.Id == nil {
|
|
// Validate JSON if provided.
|
|
var meta json.RawMessage
|
|
if metaBytes != nil {
|
|
if !json.Valid(metaBytes) {
|
|
return fmt.Errorf("subscription details invalid json")
|
|
}
|
|
meta = json.RawMessage(metaBytes)
|
|
}
|
|
|
|
id := MustNewCartId().String()
|
|
|
|
g.SubscriptionDetails[id] = &SubscriptionDetails{
|
|
Id: id,
|
|
Version: 1,
|
|
OfferingCode: m.OfferingCode,
|
|
SigningType: m.SigningType,
|
|
Meta: meta,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Update existing entry.
|
|
existing, ok := g.SubscriptionDetails[*m.Id]
|
|
if !ok {
|
|
n := &SubscriptionDetails{
|
|
Id: *m.Id,
|
|
Version: 1,
|
|
OfferingCode: m.OfferingCode,
|
|
SigningType: m.SigningType,
|
|
Meta: json.RawMessage(metaBytes),
|
|
}
|
|
g.SubscriptionDetails[*m.Id] = n
|
|
existing = n
|
|
}
|
|
changed := false
|
|
if m.OfferingCode != "" {
|
|
existing.OfferingCode = m.OfferingCode
|
|
changed = true
|
|
}
|
|
if m.SigningType != "" {
|
|
existing.SigningType = m.SigningType
|
|
changed = true
|
|
}
|
|
if metaBytes != nil {
|
|
if !json.Valid(metaBytes) {
|
|
return fmt.Errorf("subscription details invalid json")
|
|
}
|
|
existing.Meta = json.RawMessage(metaBytes)
|
|
changed = true
|
|
}
|
|
if changed {
|
|
existing.Version++
|
|
}
|
|
return nil
|
|
}
|