relay.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package relay
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "strings"
  9. graphql "github.com/graph-gophers/graphql-go"
  10. )
  11. func MarshalID(kind string, spec interface{}) graphql.ID {
  12. d, err := json.Marshal(spec)
  13. if err != nil {
  14. panic(fmt.Errorf("relay.MarshalID: %s", err))
  15. }
  16. return graphql.ID(base64.URLEncoding.EncodeToString(append([]byte(kind+":"), d...)))
  17. }
  18. func UnmarshalKind(id graphql.ID) string {
  19. s, err := base64.URLEncoding.DecodeString(string(id))
  20. if err != nil {
  21. return ""
  22. }
  23. i := strings.IndexByte(string(s), ':')
  24. if i == -1 {
  25. return ""
  26. }
  27. return string(s[:i])
  28. }
  29. func UnmarshalSpec(id graphql.ID, v interface{}) error {
  30. s, err := base64.URLEncoding.DecodeString(string(id))
  31. if err != nil {
  32. return err
  33. }
  34. i := strings.IndexByte(string(s), ':')
  35. if i == -1 {
  36. return errors.New("invalid graphql.ID")
  37. }
  38. return json.Unmarshal([]byte(s[i+1:]), v)
  39. }
  40. type Handler struct {
  41. Schema *graphql.Schema
  42. }
  43. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  44. var params struct {
  45. Query string `json:"query"`
  46. OperationName string `json:"operationName"`
  47. Variables map[string]interface{} `json:"variables"`
  48. }
  49. if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
  50. http.Error(w, err.Error(), http.StatusBadRequest)
  51. return
  52. }
  53. response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
  54. responseJSON, err := json.Marshal(response)
  55. if err != nil {
  56. http.Error(w, err.Error(), http.StatusInternalServerError)
  57. return
  58. }
  59. w.Header().Set("Content-Type", "application/json")
  60. w.Write(responseJSON)
  61. }