Operation Names & Variables
So far we've pasted values straight into the query text: book(id: "4"). Real apps don't do that. Building query strings by concatenation is error-prone, prevents caching of the query text and invites injection bugs. Instead, GraphQL has variables: the query declares typed placeholders, and the values travel separately as JSON.
Naming an operation
First, give the operation a type keyword and a name:
query BookDetails {
book(id: "4") { title }
}The name (BookDetails) is optional for a single anonymous query, but recommended: it appears in server logs, tracing and dev tools, which makes debugging much easier. It is required as soon as a document contains several operations.
Declaring variables
Variables are declared after the operation name, each with a $ prefix and a type, then used in place of literal values:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Book { id: ID, title: String, year: Int }
type Query { book(id: ID!): Book }
`);
const books = [
{ id: '1', title: 'Middlemarch', year: 1871 },
{ id: '2', title: 'Persuasion', year: 1817 },
];
const rootValue = { book: ({ id }) => books.find((b) => b.id === id) };
// The query text never changes...
const query = `
query BookDetails($bookId: ID!) {
book(id: $bookId) { title year }
}
`;
// ...only the variables do.
for (const bookId of ['1', '2']) {
const result = await graphql({
schema,
source: query,
rootValue,
variableValues: { bookId },
});
console.log(JSON.stringify(result.data));
}{"book":{"title":"Middlemarch","year":1871}}
{"book":{"title":"Persuasion","year":1817}}
Over HTTP the request body becomes {"query": "...", "variables": {"bookId": "1"}, "operationName": "BookDetails"}.
Default values and optional variables
A variable can have a default ($limit: Int = 3). A nullable variable without a default may simply be left out; the argument is then treated as not provided:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Query { topScores(limit: Int, minScore: Int): [Int] }
`);
const scores = [98, 91, 87, 75, 64, 52];
const rootValue = {
topScores: ({ limit = 10, minScore = 0 }) =>
scores.filter((s) => s >= minScore).slice(0, limit),
};
const query = `
query Leaderboard($limit: Int = 3, $minScore: Int) {
topScores(limit: $limit, minScore: $minScore)
}
`;
const runWith = async (variableValues) => {
const result = await graphql({ schema, source: query, rootValue, variableValues });
console.log(JSON.stringify(variableValues), '->', JSON.stringify(result.data.topScores));
};
await runWith({});
await runWith({ limit: 5 });
await runWith({ limit: 5, minScore: 80 });{} -> [98,91,87]
{"limit":5} -> [98,91,87,75,64]
{"limit":5,"minScore":80} -> [98,91,87]
Variables are type-checked
The engine coerces and checks variable values before execution. A wrong type or a missing required variable produces an error and no resolvers run:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`type Query { square(n: Int!): Int }`);
const rootValue = { square: ({ n }) => n * n };
const query = 'query Square($n: Int!) { square(n: $n) }';
for (const variableValues of [{ n: 12 }, { n: 'twelve' }, {}]) {
const result = await graphql({ schema, source: query, rootValue, variableValues });
console.log(result.errors ? result.errors[0].message : JSON.stringify(result.data));
}{"square":144}
Variable "$n" got invalid value "twelve"; Int cannot represent non-integer value: "twelve"
Variable "$n" of required type "Int!" was not provided.
The variable's declared type must also be compatible with the argument it's used in: passing an Int variable to a String argument is a validation error.
Choosing one of several operations
A document may hold several named operations. The client sends operationName to choose which one runs:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`type Query { hello: String, time: String }`);
const rootValue = { hello: 'Hi there', time: '12:00' };
const twoOperations = `
query Greeting { hello }
query Clock { time }
`;
const a = await graphql({ schema, source: twoOperations, rootValue, operationName: 'Clock' });
console.log(JSON.stringify(a.data));
const b = await graphql({ schema, source: twoOperations, rootValue });
console.log(b.errors[0].message);{"time":"12:00"}
Must provide operation name if query contains multiple operations.
Summary
| Syntax | Meaning |
|---|---|
query Name { … } |
named operation |
($id: ID!) |
required variable |
($limit: Int = 10) |
variable with a default |
book(id: $id) |
use the variable as an argument value |
variableValues / "variables" |
where the values go (graphql-js / HTTP) |
Tip: Never build queries with template strings like
`{ book(id: "${userInput}") }`. Use variables: they are validated by type, can't break the query syntax, and keep the query text cacheable.
Test yourself
How is a variable declared in an operation?
query Q(id: ID!)query Q($id: ID!)query Q(@id: ID!)query Q[$id: ID!]
Which graphql-js option passes the values of variables?
rootValuecontextValuevariableValuesargs
When must you send operationName?
- Always
- Never
- When the document contains more than one operation
- Only for mutations