Co-authored-by: matst80 <mats.tornberg@gmail.com> Reviewed-on: #8 Co-authored-by: Mats Törnberg <mats@tornberg.me> Co-committed-by: Mats Törnberg <mats@tornberg.me>
66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package cart
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
messages "git.k6n.net/go-cart-actor/proto/cart"
|
|
)
|
|
|
|
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 {
|
|
return fmt.Errorf("subscription details with id %s not found", *m.Id)
|
|
}
|
|
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
|
|
}
|