Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly declare a GraphQL query without parameters.

I'm using vs code + graphql-cli for validating & linting the schema. In the following declaration (in the graphql schema file):

type Query {
  users(): Int
}

The users declaration above is marked as en error, but it doesn't make any problem (or warning) by the server - it's only vs code and graphql lint reporting it as an error:

2:9 Syntax Error: Expected Name, found )  undefined

If I add a parameter to the query, eg:

type Query {
  users(n: Int): Int
}

then there is no problem reported by vs code or graphql-cli. How can I properly declare a graphql query without parameters.

like image 416
Robert Zaremba Avatar asked Oct 11 '18 22:10

Robert Zaremba


People also ask

How do you pass parameters in GraphQL query?

When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map. . then(data => console.

How do you define variables in GraphQL?

Variables simplify GraphQL queries and mutations by letting you pass data separately. A GraphQL request can be split into two sections: one for the query or mutation, and another for variables. Variables can be declared after the query or mutation and are passed like arguments to a function and begin with $ .

What is __ Typename in GraphQL?

The __typename field returns the object type's name as a String (e.g., Book or Author ). GraphQL clients use an object's __typename for many purposes, such as to determine which type was returned by a field that can return multiple types (i.e., a union or interface).


1 Answers

The queries you specify in your schema behave just like any other field on a particular type (the main difference is that their type is linked to a particular operation). If you don't want to declare any arguments for a particular field, you just omit the parentheses entirely. The same goes for queries and mutations:

type Query {
  users: Int
}

From the spec:

Fields are conceptually functions which return values, and occasionally accept arguments which alter their behavior. These arguments often map directly to function arguments within a GraphQL server’s implementation.

So it's worthwhile pointing out that any Type's field could have arguments. For example, a query could look like this:

query UsersQuery {
  users {
    name
    posts (onlyNew: true) {
      title
    }
  }
}
like image 110
Daniel Rearden Avatar answered Oct 16 '22 16:10

Daniel Rearden