According to the Ariadne's documentation, it should be possible to define field aliases with set_alias
. But I can't make it work, set_alias
does not complain but any query for the alias field returns null.
# test.py
from ariadne import ObjectType, gql, make_executable_schema
from ariadne.asgi import GraphQL
from types import SimpleNamespace
type_defs = gql("""
type Query {
hello: String!
goodbye: String!
}
""")
query = ObjectType("Query")
@query.field("hello")
def resolve_hello(_, info):
request = info.context['request']
user_agent = request.headers.get('user-agent', 'guest')
return 'hello, %s' % user_agent
query.set_alias('goodbye', 'hello')
schema = make_executable_schema(type_defs, query )
app = GraphQL(schema, debug=True)
which I run with uvicorn test:app
So what is the proper way to define an alias?
That's not what set_alias
do. set_alias
can only alias an existing attribute (not resolver) in the resolved object. So let say that you have a field user
that resolves to an object with attributes first_name
and last_name
you can define an alias first
that maps to first_name
. So in essence set_alias
gives you a convenient syntax to define resolvers that map to an object's attribute:
from ariadne import QueryType, ObjectType, gql, make_executable_schema
from ariadne.asgi import GraphQL
from types import SimpleNamespace
type_defs = gql("""
type Query {
user: User
}
type User {
username: String!
first: String
last: String
}
""")
query = QueryType()
@query.field("user")
def resolve_user(obj, info):
to_return = SimpleNamespace()
to_return.first_name = 'Rubén'
to_return.last_name = 'Laguna'
return to_return
user = ObjectType("User")
@user.field("username")
def resolve_username(obj, info):
return f"{obj.first_name} {obj.last_name}"
user.set_alias('last', 'last_name')
user.set_alias('first', 'first_name')
schema = make_executable_schema(type_defs, query, user)
app = GraphQL(schema, debug=True)
A query for {user { first}}
will return {"data": {"user": {"first": "Rubén"}}}
without having to provide a full fledge resolver for first
.