graphiql
graphiql copied to clipboard
"Must provide an operation." error
I have a simple project like the below one. the database works fine because when I request this endpoint :
http://localhost:8080/api?query={movie(id:1){name}}
I get a proper response. But when I do the same with graphiql endpoint like this :
http://localhost:8080/graphiql?query={movie(id:1){name}}
I get this error :
{
"data": null,
"errors": [
{
"message": "Must provide an operation.",
"locations": []
}
]
}
Project:
var movieType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Movie",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.Int,
},
"name": &graphql.Field{
Type: graphql.String,
},
"year": &graphql.Field{
Type: graphql.Int,
},
"directorId": &graphql.Field{
Type: graphql.Int,
},
"seriesId": &graphql.Field{
Type: graphql.Int,
},
},
},
)
var queryType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"movie": &graphql.Field{
Type: movieType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
id, ok := p.Args["id"].(int)
if ok {
for _, movie := range movies {
if int(movie.ID) == id {
return movie, nil
}
}
}
return nil, nil
},
},
},
})
var schema, _ = graphql.NewSchema(
graphql.SchemaConfig{
Query: queryType,
},
)
func executeQuery(query string, schema graphql.Schema) *graphql.Result {
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) > 0 {
fmt.Printf("errors: %v", result.Errors)
}
return result
}
func main() {
graphiqlHandler, err := graphiql.NewGraphiqlHandler("/api")
if err != nil {
panic(err)
}
http.HandleFunc("/api", func(rw http.ResponseWriter, r *http.Request) {
result := executeQuery(r.URL.Query().Get("query"), schema)
json.NewEncoder(rw).Encode(result)
})
http.Handle("/graphiql", graphiqlHandler)
http.ListenAndServe(":8080", nil)
}