Fields
At its simplest, GraphQL is about asking for specific fields on objects. A field can hold a scalar (a leaf value like a string or number) or another object, in which case you must say which of its fields you want. This nesting is what makes one GraphQL request replace several REST calls.
Scalar fields and object fields
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Author {
name: String
country: String
}
type Book {
title: String
year: Int
author: Author
}
type Query {
featuredBook: Book
}
`);
const rootValue = {
featuredBook: {
title: 'The Left Hand of Darkness',
year: 1969,
author: { name: 'Ursula K. Le Guin', country: 'USA' },
},
};
const query = `{
featuredBook {
title
author {
name
}
}
}`;
const result = await graphql({ schema, source: query, rootValue });
console.log(JSON.stringify(result, null, 2));{
"data": {
"featuredBook": {
"title": "The Left Hand of Darkness",
"author": {
"name": "Ursula K. Le Guin"
}
}
}
}
title is a leaf (a String), so it needs no braces. author returns an Author object, so it must be followed by a selection set { name }.
Every object needs a selection
You can't ask for an object "as a whole": GraphQL never guesses which fields you want. Both mistakes below are caught by validation:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Author { name: String }
type Book { title: String, author: Author }
type Query { featuredBook: Book }
`);
const tryQuery = async (source) => {
const result = await graphql({ schema, source, rootValue: {} });
console.log(source, '->', result.errors[0].message);
};
await tryQuery('{ featuredBook }'); // object without selection
await tryQuery('{ featuredBook { title { x } } }'); // selection on a leaf{ featuredBook } -> Field "featuredBook" of type "Book" must have a selection of subfields. Did you mean "featuredBook { ... }"?
{ featuredBook { title { x } } } -> Field "title" must not have a selection since type "String" has no subfields.
Lists of objects
When a field returns a list, the selection set applies to each item. You write the selection once, and every element comes back with those fields:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Book { title: String, year: Int, pages: Int }
type Query { books: [Book] }
`);
const rootValue = {
books: [
{ title: 'Dune', year: 1965, pages: 412 },
{ title: 'Neuromancer', year: 1984, pages: 271 },
{ title: 'Kindred', year: 1979, pages: 264 },
],
};
const result = await graphql({
schema,
source: '{ books { title year } }',
rootValue,
});
console.log(JSON.stringify(result.data.books));[{"title":"Dune","year":1965},{"title":"Neuromancer","year":1984},{"title":"Kindred","year":1979}]
Fields computed on the fly
A field doesn't have to be stored anywhere. If an object's property is a function, graphql-js calls it when (and only when) the field is requested. Here ageInYears is derived from year:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Book { title: String, year: Int, ageInYears: Int }
type Query { books: [Book] }
`);
class Book {
constructor(title, year) {
this.title = title;
this.year = year;
}
ageInYears() {
console.log(`computing age of ${this.title}`);
return 2026 - this.year;
}
}
const rootValue = { books: [new Book('Dune', 1965), new Book('Kindred', 1979)] };
const first = await graphql({ schema, source: '{ books { title } }', rootValue });
console.log(JSON.stringify(first.data));
const second = await graphql({ schema, source: '{ books { title ageInYears } }', rootValue });
console.log(JSON.stringify(second.data));{"books":[{"title":"Dune"},{"title":"Kindred"}]}
computing age of Dune
computing age of Kindred
{"books":[{"title":"Dune","ageInYears":61},{"title":"Kindred","ageInYears":47}]}
The first query never triggered ageInYears. This is a key GraphQL idea: expensive work only happens for fields the client actually selects.
The __typename field
Every object type has a hidden field, __typename, that returns the name of its type. Clients use it for caching and to tell types apart (you'll need it for interfaces and unions):
{ featuredBook { __typename title author { __typename name } } }returns "__typename": "Book" and "__typename": "Author" next to the other fields.
Field order
The response keeps the same field order as the query, not the order in the schema. If you ask for { year title }, year comes first. Clients can rely on this.
Test yourself
Which query is valid if author returns an Author object type?
{ book { author } }{ book { author { name } } }{ book { author: name } }{ book { author() } }
A field resolver that is a method on the source object runs…
- Once when the server starts
- For every query, whether or not the field is selected
- Only when the field is selected
- Never; methods are ignored
What does __typename return?
- The schema version
- The name of the object's GraphQL type
- The JavaScript class name
- The field's return type