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.
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.
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 $ .
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).
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With