Reputation: 331
I have graphql schema like this:
type Query {
user: User!;
}
type User {
height(measurementSystem: String!): String!;
}
is it possible by graphql specification to query user like this?
query {
user {
heightInMeters: height("metric")
heightInFeet: height("imperial")
}
}
and get something like this
data: {
user: {
heightInMeters: "1.8",
heightInFeet: "5'9"
}
}
As I can see in doc - https://graphql.org/learn/queries/#aliases, aliases are like renaming field to another name, but does it support to request the same fields with different arguments with different aliases? Or my only option is to do the same query with different arguments for this field?
query {
userWithHeightInMeters: user {
height("metric")
}
userWithHeightInFeet: user {
height("imperial")
}
}
Upvotes: 0
Views: 354
Reputation: 647
It is possible to query the same field with different arguments, you would just need to handle the different arguments.
Using Graphene-Django to demonstrate, this is what a working example of the above would look like:
class UserType(DjangoObjectType):
...
# Define the property
height = graphene.Field(
graphene.Float,
unit=graphene.String()
)
# Define the property resolver
def resolve_height(self, info, unit):
height = 1.67
if unit == "metric":
return height
elif unit == "imperial":
return height * 3.28084
In your query, set the alias with the field name:
query {
user {
heightInMetres: height(unit: "metric"),
heightInFeet: height(unit: "imperial"),
}
}
Your output will include the values as specified:
{
user {
"heightInMetres": 1.67,
"heightInFeet": 5.4790028,
}
}
While the GraphQL documentation is meant to be language-agnostic, I hope the above helps, regardless of what labguage you choose.
Upvotes: 1