In GraphQL, is there any way to alias the returned value using an input argument?
e.g. here:
query GetCurrencyRevenueAggregate(
$currency: String!
$startDate: timestamptz!
$endDate: timestamptz!
) {
DailyCurrencyRevenue_aggregate(
where: {
currency: { _eq: $currency }
dateTimestamp: { _gte: $startDate, _lt: $endDate }
}
) {
aggregate {
sum {
amountETH: amount # <--- see this
}
}
}
}
I would like to alias amountETH
to amount_{$currency}
Is this possible in GraphQL?
GraphQL intentionally avoids dynamic field names to keep the response shape predictable and type-safe. Aliases are part of the query document and must be static at parse time. A workaround is to query with a static (or no) alias, then rename the key in your client-side code:
const amount = data.DailyCurrencyRevenue_aggregate.aggregate.sum.amount;
const aliased = { [`amount_${variables.currency}`]: amount };
You could also generate the query with the alias baked in but this brings its fair share of sanitisation issues and cache/persisted-query misses.
const alias = `amount_${currency}`;
const query = `
query ($currency: String!, $startDate: timestamptz!, $endDate: timestamptz!) {
DailyCurrencyRevenue_aggregate(where:{
currency:{_eq:$currency}
dateTimestamp:{_gte:$startDate,_lt:$endDate}
}) {
aggregate { sum { ${alias}: amount } }
}
}
`;