-
Notifications
You must be signed in to change notification settings - Fork 220
/
graphql.go
71 lines (56 loc) · 1.77 KB
/
graphql.go
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
71
package handlers
import (
"context"
"encoding/json"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/spaceuptech/space-cloud/model"
"github.com/spaceuptech/space-cloud/utils/graphql"
)
// HandleGraphQLRequest creates the graphql operation endpoint
func HandleGraphQLRequest(graphql *graphql.Module) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Create a context of execution
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
vars := mux.Vars(r)
projectID := vars["project"]
pid := graphql.GetProjectID()
// Load the request from the body
req := model.GraphQLRequest{}
json.NewDecoder(r.Body).Decode(&req)
defer r.Body.Close()
w.Header().Set("Content-Type", "application/json")
if projectID != pid {
// throw some error
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "project id doesn't match"})
return
}
// Get the path parameters
token := getRequestMetaData(r).token
ch := make(chan struct{}, 1)
graphql.ExecGraphQLQuery(ctx, &req, token, func(op interface{}, err error) {
defer func() { ch <- struct{}{} }()
if err != nil {
errMes := map[string]interface{}{"message": err.Error()}
json.NewEncoder(w).Encode(map[string]interface{}{"errors": []interface{}{errMes}})
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{"data": op})
return
})
select {
case <-ch:
return
case <-time.After(10 * time.Second):
log.Println("GraphQL Handler: Request timed out")
errMes := map[string]interface{}{"message": "GraphQL Handler: Request timed out"}
json.NewEncoder(w).Encode(map[string]interface{}{"errors": []interface{}{errMes}})
return
}
}
}