Aliases
The bookshop home page has two shelves side by side: "Fantasy picks" and "Mystery picks". Both come from the same field, books, with different genres. Ask for books twice in one query and the server refuses, because the response would need two keys called books. Aliases solve this.
The rule
newName: fieldrenames the key; it lets one field be asked twice.
An alias goes before a field, followed by a colon. It changes the key in the response, and nothing else:
{
fantasy: books(genre: FANTASY, first: 2) {
title
}
mystery: books(genre: MYSTERY, first: 2) {
title
}
}{
"data": {
"fantasy": [{ "title": "The Salt Road" }, { "title": "Lanterns at Dusk" }],
"mystery": [{ "title": "The Quiet Ledger" }, { "title": "Nine Locked Doors" }]
}
}Each field in a response has a response name: its alias if it has one, otherwise its field name. Inside one selection set, two fields with the same response name must be mergeable, which means the same field with the same arguments. So:
title titleis fine; the two merge into onetitlekey.books(genre: FANTASY) { title } books(genre: MYSTERY) { title }is an error; one key cannot hold two different answers.
Aliases are also handy for renaming a key to suit your code, such as heading: title. The schema and the resolver are untouched; only the JSON key changes.
Aliases work at any depth, not just at the root. A book page that wants the single newest review for a banner and the five newest for a list can ask for both inside one book:
{
book(id: "b1") {
newest: reviews(first: 1) { rating text }
recent: reviews(first: 5) { rating }
}
}The shortcut
Before sending, scan each selection set for repeated response names. If two share a name but differ in arguments, give at least one an alias.
List the response names
Two fields called
booksat the root.
A frequent mix-up is the direction of the colon. The new name comes first: heading: title, not title: heading. Read it as "heading is title".
Drills
Answer fast — trust the rule.
What key holds the result of { cheapest: books(first: 1) { title } }?
Why is { books(genre: FANTASY) { title } books(genre: MYSTERY) { title } } rejected?
Is { book(id: "b1") { title title } } valid?
You want the book's title to appear under the key heading. Which is right?
Remember
newName: fieldrenames the key; it lets one field be asked twice.- Scan each selection set: same response name plus different arguments means add an alias.
- Trap: the colon direction; the alias comes first.
