aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/graph-gophers/graphql-go/relay/relay.go
blob: 78e4dfdd51d53bdd84758b1c5654cb6d33a2330a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package relay

import (
    "encoding/base64"
    "encoding/json"
    "errors"
    "fmt"
    "net/http"
    "strings"

    graphql "github.com/graph-gophers/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)
}

type Handler struct {
    Schema *graphql.Schema
}

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    var params struct {
        Query         string                 `json:"query"`
        OperationName string                 `json:"operationName"`
        Variables     map[string]interface{} `json:"variables"`
    }
    if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
    responseJSON, err := json.Marshal(response)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
}