Ejemplo n.º 1
0
func main() {
	var doc graphql.Document
	fs, _ := os.Open("./tests/relay-todo.graphql")
	if err := parser.New("graphql", fs).Decode(&doc); err != nil {

		log.Printf(err.Error())

	} else {

		log.Printf(prettyprint.AsJSON(doc))
		log.Print(doc.DefinitionSize)
	}

	parser.InlineFragments(&doc)
	log.Printf(prettyprint.AsJSON(doc.Operations[0]))
}
Ejemplo n.º 2
0
// ServeHTTP provides an entrypoint into a graphql executor. It pulls the query from
// the 'q' GET parameter.
func (h *ExecutorHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers"))
	if r.Method == "OPTIONS" {
		w.WriteHeader(200)
		return
	}

	decoder := json.NewDecoder(r.Body)
	var qreq Request
	err := decoder.Decode(&qreq)
	if err != nil {
		log.Println("error parsing:", err)
		writeErr(w, err)
		return
	}
	q := qreq.Query

	h.mutex.Lock()
	/*
		//TODO(tallstreet): reject non-GET/OPTIONS requests
	*/
	var doc graphql.Document
	if err := parser.New("graphql", strings.NewReader(q)).Decode(&doc); err != nil {

		h.mutex.Unlock()
		log.Println("error parsing graphql:", err.Error())
		writeErr(w, err)
		return

	}
	h.mutex.Unlock()

	parser.InlineFragments(&doc)

	var result = Result{}
	for o := range doc.Operations {
		operation := doc.Operations[o]
		asjson, _ := json.MarshalIndent(operation, "", " ")
		log.Println(string(asjson))
		// if err := h.validator.Validate(operation); err != nil { writeErr(w, err); return }
		ctx := context.Background()
		if r.Header.Get("X-Trace-ID") != "" {
			t, err := tracer.FromRequest(r)
			if err == nil {
				ctx = tracer.NewContext(ctx, t)
			}
		}
		ctx = context.WithValue(ctx, "http_request", r)
		ctx = context.WithValue(ctx, "variables", qreq.Variables)
		if r.Header.Get("X-GraphQL-Only-Parse") == "1" {
			writeJSONIndent(w, operation, " ")
			return
		}

		data, err := h.executor.HandleOperation(ctx, operation)
		if err != nil {
			w.WriteHeader(400)
			result.Error = &Error{Message: err.Error()}
		} else {
			result.Data = data
		}
		if t, ok := tracer.FromContext(ctx); ok {
			t.Done()
			result.Trace = t
		}
	}

	writeJSONIndent(w, result, "  ")
}