sorare/graphql/id.go

36 lines
619 B
Go

package graphql
import (
"encoding/json"
"strings"
"github.com/pkg/errors"
)
type Id struct {
Type string
Value string
}
func (i Id) MarshalJSON() ([]byte, error) {
return []byte(`"` + i.Type + `:` + i.Value + `"`), nil
}
func (i *Id) UnmarshalJSON(bytes []byte) error {
var s string
if err := json.Unmarshal(bytes, &s); err != nil {
return err
}
splits := strings.Split(s, ":")
if len(splits) < 2 {
return errors.New("invalid id")
}
i.Value = splits[len(splits)-1]
i.Type = strings.Join(splits[:len(splits)-1], ":")
return nil
}
func (i Id) String() string {
return i.Type + ":" + i.Value
}