How to add Enum resolver to Flask GraphQL server using Ariadne #874
Replies: 3 comments 2 replies
-
The document is very unclear. An example will be great! |
Beta Was this translation helpful? Give feedback.
-
There are no resolvers for enums per se. Only Here's minimal example where Python enum is mapped to GraphQL enum, and what this means when enum is used as field's argument or return value: from enum import Enum
from ariadne import EnumType, QueryType, gql, make_executable_schema, graphql_sync
class UserRole(str, Enum):
ADMIN = "adm"
USER = "usr"
type_defs = gql(
"""
type Query {
getEnum(enum: Role): String
enumFromEnum: Role!
enumFromStr: Role!
}
enum Role {
ADMIN
USER
}
"""
)
role_enum = EnumType("Role", UserRole)
query_type = QueryType()
@query_type.field("getEnum")
def resolve_get_enum(*_, enum):
# EnumType tells GraphQL how to map GraphQL enums to python values
# enum is member of UserRole
return repr(enum)
@query_type.field("enumFromEnum")
def resolve_enum_from_enum(*_):
# EnumType tells GraphQL how to map python enums to GraphQL enums
# so returning "UserRole.ADMIN" will return "ADMIN" in GraphQL
return UserRole.ADMIN
@query_type.field("enumFromStr")
def resolve_enum_from_str(*_):
# EnumType tells GraphQL how to map python values to GraphQL enums
# so returning "usr" will return "USER" in GraphQL
return "usr"
schema = make_executable_schema(type_defs, query_type, role_enum)
_, result = graphql_sync(
schema,
{
"query": (
"""
{
getEnum(enum: USER)
enumFromEnum
enumFromStr
}
"""
)
},
)
assert result == {
"data": {
"getEnum": "<UserRole.USER: 'usr'>",
"enumFromEnum": "ADMIN",
"enumFromStr": "USER",
}
} |
Beta Was this translation helpful? Give feedback.
-
Edit: See @rafalp 's complete example. Ok. Here is an example on how to use the post_weight = EnumType("PostWeight", PostWeight)
# this is how to use it
schema = make_executable_schema(type_defs, query, post_weight)
app = GraphQL(schema) |
Beta Was this translation helpful? Give feedback.
-
I want to pass a custom resolver for enum type into my GraphQL server created using Flask and Ariadne.
In my schema.graphql file, I have defined an enum:
And I want to assign values to each enum field like this:
This is my GraphQL API:
Now, I need to pass this utilization_score to my GraphQL server, which I have no idea how to do.
In the Ariadne documentation, I found this statement - (In my case, I have utilization_score instance instead of post_weight instance)
Include the post_weight instance in list of types passed to your GraphQL server, and it will automatically translate Enums between their GraphQL and Python values.
But I still couldn't figure out where to pass this enum resolver instance.
Beta Was this translation helpful? Give feedback.
All reactions