Reputation: 710
Is there a way to execute a function before all query?
When I add an annotation above Query class, It makes an error
AssertionError: Type <function Query at 0x104d1dd30> is not a valid ObjectType.
def my_func(f):
@wraps(f)
def my_func_wrap(*args, **kwargs):
//do something
return f(*args, **kwargs)
return my_func_wrap
@my_func
class Query(graphene.ObjectType):
node = relay.Node.Field()
users = graphene.List(lambda: UserSchema)
def resolve_users(self, info):
//do something
return User.query.all()
schema = graphene.Schema(query=Query)
If i add the annotation to every resolver, It works fine.
but I will add more than 20 resolvers and I don't think adding the annotation to every resolver is good idea.
Upvotes: 0
Views: 590
Reputation: 96
Yes, you can. Just create a custom View class inheriting from GraphQLView
and override dispatch
method then use your own view class as graphql endpoint handler. Something like this:
class CustomGraphQLView(GraphQLView):
def dispatch(self, request, *args, **kwargs):
// do something
super(CustomGraphqlView, self).dispatch(request, *args, **kwargs)
If you want to manipulate the queryset itself, I suggest to use graphene-django-extras
and override the list_resolver
method on its query fields(DjangoFilterListField
, DjangoFilterPaginateListField
, ...) class and use your own custom class.
You can call super on override methods or copy the exact code from their source and edit them.
Upvotes: 1