carpool-service/interoperability/ocss/prices.go

72 lines
1.5 KiB
Go

package ocss
import (
"bytes"
"encoding/json"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
)
type PriceType int64
const (
Free PriceType = iota
Paying
Unknown
)
var priceTypeToID = map[string]PriceType{
"FREE": Free,
"PAYING": Paying,
"UNKNOWN": Unknown,
}
var priceTypeToString = map[PriceType]string{
Free: "FREE",
Paying: "PAYING",
Unknown: "UNKNOWN",
}
func (s PriceType) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
buffer.WriteString(priceTypeToString[s])
buffer.WriteString(`"`)
return buffer.Bytes(), nil
}
func (s PriceType) MarshalBSONValue() (bsontype.Type, []byte, error) {
return bson.MarshalValue(priceTypeToString[s])
}
func (bs *PriceType) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
// Note that if the string cannot be found then it will be set to the zero value, 'Created' in this case.
*bs = priceTypeToID[j]
return nil
}
func (bs *PriceType) UnmarshalBSONValue(t bsontype.Type, b []byte) error {
if t == bsontype.Null || len(b) == 0 {
return nil
}
j, _, ok := bsoncore.ReadString(b)
if !ok {
return fmt.Errorf("cannot parse status")
}
*bs = priceTypeToID[j]
return nil
}
type Price struct {
Type *PriceType `json:"type,omitempty" bson:"type,omitempty"`
Amount *float64 `json:"amount,omitempty" bson:"amount,omitempty"`
Currency *string `json:"currency,omitempty" bson:"currency,omitempty"`
}