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 }
}
}