Renaming fields in GraphQL queries — Aliases
16 октября 2024 г.
In a GraphQL query, you can rename a field in the response. This is useful when you need to run two identical queries with different variables and distinguish their results.
This feature is called aliases.
The structure for renaming a field is: newFieldName: oldFieldName
For example, suppose you need to fetch a list of transactions by hash—one for buy transactions and one for sell transactions. You also need to display the transaction type, but the API does not return it. In this case, you can rename a field in the query and use that name on the frontend to determine the type.
Let’s rename the id field.
JavaScript
1// Below, I rename the id field to buyId.2query Transactions($hash_in: [Bytes!] = "") {3 transactions(4 where: { hash_: { hash_in: $hash_in } }5 ) {6 amount7 timestamp8 buyId: id9 }10}1112// Then, when displaying data on the frontend, you can use this key as a reference.13if ("buyId" in item) {14 return "Buy"15}16return "Sell"17