From 947a1a3a8a25fd0821569a402dd433c751c58787 Mon Sep 17 00:00:00 2001 From: Richard Musiol Date: Tue, 1 Nov 2016 13:49:22 +0100 Subject: [PATCH] added package with tools for Relay --- relay/relay.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 relay/relay.go diff --git a/relay/relay.go b/relay/relay.go new file mode 100644 index 00000000000..daa791a7755 --- /dev/null +++ b/relay/relay.go @@ -0,0 +1,44 @@ +package relay + +import ( + "encoding/base64" + "errors" + "fmt" + "strings" + + "encoding/json" + + graphql "github.com/neelance/graphql-go" +) + +func MarshalID(kind string, spec interface{}) graphql.ID { + d, err := json.Marshal(spec) + if err != nil { + panic(fmt.Errorf("relay.MarshalID: %s", err)) + } + return graphql.ID(base64.URLEncoding.EncodeToString(append([]byte(kind+":"), d...))) +} + +func UnmarshalKind(id graphql.ID) string { + s, err := base64.URLEncoding.DecodeString(string(id)) + if err != nil { + return "" + } + i := strings.IndexByte(string(s), ':') + if i == -1 { + return "" + } + return string(s[:i]) +} + +func UnmarshalSpec(id graphql.ID, v interface{}) error { + s, err := base64.URLEncoding.DecodeString(string(id)) + if err != nil { + return err + } + i := strings.IndexByte(string(s), ':') + if i == -1 { + return errors.New("invalid graphql.ID") + } + return json.Unmarshal([]byte(s[i+1:]), v) +}