Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Must provide an operation." error #9

Open
masoud-moeini opened this issue Jan 13, 2022 · 0 comments
Open

"Must provide an operation." error #9

masoud-moeini opened this issue Jan 13, 2022 · 0 comments

Comments

@masoud-moeini
Copy link

masoud-moeini commented Jan 13, 2022

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant