func ExampleParse() {
	result, err := parser.ParseOperation([]byte(exampleQuery))
	if err != nil {
		fmt.Println("err:", err)
	} else {
		asjson, _ := json.MarshalIndent(result, "", " ")
		fmt.Println(string(asjson))
	}
	// output:
	// {
	//  "Type": "query",
	//  "SelectionSet": [
	//   {
	//    "Field": {
	//     "Name": "foo",
	//     "SelectionSet": [
	//      {
	//       "Field": {
	//        "Name": "field"
	//       }
	//      }
	//     ]
	//    }
	//   }
	//  ]
	// }
}
Exemple #2
0
func TestMalformedQuery(t *testing.T) {
	op, err := parser.ParseOperation(nil)
	if !parser.IsMalformedOperation(err) {
		t.Error("Expected malformed operation")
	}
	if op != nil {
		t.Error("Expected nil result")
	}
	if es := err.Error(); es != "parser: malformed graphql operation: 1:1 (0): no match found" {
		t.Errorf("got unexpected error: '%v'", es)
	}
}
Exemple #3
0
func TestMultipleOperations(t *testing.T) {
	multi := `
	{foo}
	{bar}
	`
	op, err := parser.ParseOperation([]byte(multi))
	if err != parser.ErrMultipleOperations {
		t.Error("Expected multiple operations error")
	}
	if op != nil {
		t.Error("Expected nil result")
	}
}
Exemple #4
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
	}

	//TODO(tmc): reject non-GET/OPTIONS requests
	q := r.URL.Query().Get("q")
	log.Println("query:", q)
	operation, err := parser.ParseOperation([]byte(q))
	if err != nil {
		log.Println("error parsing:", err)
		writeErr(w, err)
		return
	}
	// 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)
	if r.Header.Get("X-GraphQL-Only-Parse") == "1" {
		writeJSONIndent(w, operation, " ")
		return
	}

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

	writeJSONIndent(w, result, "  ")
}