1

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?

1
  • Have you considered using an input on the amount parameter? amount(code: CURRENCY_CODE): Int? Commented Oct 10 at 21:03

1 Answer 1

3

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 } }
    }
  }
`;
Sign up to request clarification or add additional context in comments.

1 Comment

"this brings its fair share of sanitisation issues" - yes. Make sure currency is not controlled by the user (or potentially an attacker), it could easily lead to query syntax errors or even to security issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.