For Example: If the user is member of the group, response would contain all the group information including members of the group, else response will only contain the count of members in group. I'm using graphene-django and need to return this data from a query schema.
class GroupMutation(graphene.Mutation):
group = graphene.Field(GroupType)
class Arguments:
id = graphene.ID(required=False)
created_by = graphene.ID(required=False)
admins = graphene.ID(required=False)
moderators = graphene.ID(required=False)
users = graphene.List(graphene.ID)
name = graphene.String(required = True)
public = graphene.Boolean(required=False)
location = graphene.String(required=False)
reported = graphene.Boolean(required=False)
reported_by = graphene.List(graphene.ID)
profile_picture = Upload(required=False)
background_picture = Upload(required=False)
Your GraphQL/Graphene schema will need to contain both fields, since the schema cannot conditionally change depending on the user, but you can conditionally choose to populate those fields in the response based on what the user should access.
For example:
import graphene
class GroupNode(graphene.ObjectType):
# Assume MemberNode is defined elsewhere
members = graphene.List(MemberNode)
members_count = graphene.Int()
def resolve_members(parent, info):
if info.context.user.username == 'allowed_user':
return Members.objects.all() # whatever logic you need
# Return nothing if the user is not allowed
return None
def resolve_members_count(parent, info):
if info.context.user.username == 'allowed_user':
# We don't need to return this, since the user can access `members` directly
return None
return Members.objects.count()
Note that both fields will need to be nullable (i.e. you can't pass required=True
), so that you can optionally choose to omit them in the resolve_
methids. (Alternatively, you could choose to make members
non-null with required=True
, and return []
rather than return None
, if that's more convenient.)
There are also some other types of authorization examples Graphene-Django docs, in case those are helpful.