Assa Lahav
Assa Lahav

Reputation: 51

GraphQL: Use variable value as an alias

I have this GraphQL query:

{
  timeline(limit:10){
    eventType
    level: eventSeverity
  },  
}

I would like to set the 'eventSeverity' alias name using a variable, rather than the fixed name 'level'. Something like this:

query($name:String!)
{
  timeline(limit:10){
    eventType
    $name: eventSeverity
  },  
}

But running the above yields this error:

Syntax Error GraphQL request (5:5) Expected Name, found $

Is it possible to use a variable value as an alias name at all?

Upvotes: 3

Views: 2141

Answers (1)

yachaka
yachaka

Reputation: 5579

You cannot use dynamic field name in GraphQL, but what you can do is create a field that accepts a name argument, example

query($name: String!) {
  timeline(limit: 10) {
    eventType
    eventSeverity(name: $name) // Write a resolve function that returns timeline[name]
  }
}

Upvotes: 1

Related Questions