Skip to content

Commit

Permalink
added package with tools for Relay
Browse files Browse the repository at this point in the history
  • Loading branch information
neelance committed Nov 1, 2016
1 parent 65f3e2b commit 947a1a3
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions relay/relay.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 947a1a3

Please sign in to comment.