GraphQL circular queries with one to many relationships - graphql

I'm learning GraphQL by building a simple python application, basically runs nmap scans stores output to a database, and can be queried by a GraphQL API. I seem to be a bit confused on how GraphQL works.
I have a few tables that are one-to-many relationships: user has many scans, scans have results, results have hosts, hosts have ports, hosts have os. Which I defined using sqlalchemy and used graphene
Now, in my GraphQL schema I have:
class Scans(SQLAlchemyObjectType):
class Meta:
model = ScansModel
class ScanResult(SQLAlchemyObjectType):
class Meta:
model = ScanResultModel
class Hosts(SQLAlchemyObjectType):
class Meta:
model = HostInfoModel
class Ports(SQLAlchemyObjectType):
class Meta:
model = PortInfoModel
class Os(SQLAlchemyObjectType):
class Meta:
model = OsInfoModel
class Query(graphene.ObjectType):
user = graphene.Field(User)
scans = graphene.List(Scans)
scan_results = graphene.List(ScanResult)
hosts = graphene.List(Hosts)
ports = graphene.List(Ports)
os = graphene.Field(Os)
def resolve_scans(self, info):
query = Scans.get_query(info)
return query
Now, when I make a GraphQL query, I can query scans, results, hostinfo, portinfo, osinfo, without having to have resolvers for those fields. I was under the impression that each of those fields would need a resolver.
Furthermore, I seem to be able to do circular quereis (so from scanresults I can query scans and from scans I can query user) due to the foreign keys and relationship table.
Is this the correct behaviour, or am misunderstanding how GraphQL works?

What you need to do is:
class ScanResult(SQLAlchemyObjectType):
class Meta:
model = ScanResultModel
scans = graphene.List(Scans, description="Scans from results.")
def resolve_scans(self, info):
query = Scans.get_query(info)
return query.filter(ScansModel.my_id == self.scans_id).all()
This will probably enables you to build queries like:
{
scanresult{
edges {
node {
id
scans{
id
}
}
}
}

I know that resolvers for each field with SQLAlchemyObjecType are handled inside the library.
when I use mongoengine without using MongoengineObjectType, I code like this.
class Query(graphene.ObjectType):
department = graphene.List(of_type=DepartmentField,
name=graphene.String(default_value="all"))
role = graphene.List(of_type=RoleField,
name=graphene.String(default_value="all"))
employee = graphene.List(of_type=EmployeeField,
name=graphene.String(default_value="all"))
def resolve_department(self, info, name):
if name == "all":
department = [construct(DepartmentField, object) for object in DepartmentModel.objects]
return department
else:
department = DepartmentModel.objects.get(name=name)
return [construct(DepartmentField, department)]
def resolve_role(self, info, name):
.
.
.

Related

User defined fields in graphQL

Making an employee management system with graphene-Django and I have a JsonB field that I don't know the shape of because each company will defined the shape.
Here's the model:
class Employee(models.Model):
bonuses = models.JSONField(default=dict)
#...OTHER FIELDS
here's the type:
class EmployeeType(DjangoObjectType):
class Meta:
model = Employee
fields = "__all__"
Here's the mutation class:
class EmployeeInfo(graphene.Mutation):
employee = graphene.List(EmployeeType)
class Arguments:
bonuses = GenericScalar()
#...OTHER FIELDS
def mutate(self, info, **kwargs):
#DOING STUFF
return EmployeeInfo(employee=employee)
Now, say a company wants to give bonuses to a developer with the following schema:
export const EMPLOYEE_INFO = gql`
mutation MutateEmployee(
$employeeOfTheMonth: Int
$mostPR: Int
$profitSharing: Int
) {
employeeInfo(
bonuses:{
employeeOfTheMonth: $employeeOfTheMonth
mostPR: $mostPR
profitSharing: $profitSharing
}
#...OTHER FIELDS
){....}
}
`
This is my current setup, the problem is I get only null values in the database for the bonuses field. Notice that I'm using GenericScalar which is not documented and I don't know if that's the wrong scalar.
If this is a restaurant, obviously the bonuses will be different and that's why I need a setup like this.
How can I define a field that will take user defined shapes?
I think this is what you need
class EmployeeInfo(graphene.Mutation):
employee = graphene.List(EmployeeType)
class Arguments:
bonuses = graphene.JSONString()
#...OTHER FIELDS

How to get the current logged-in user for schema? (django graphql api)

my goal: I am trying to return all the fields of the posts if the user has an id of 1, and I want to return only 3 fields if else.
My problem is: in the query or mutations I can do info.context.user.id but in the schema I can't do that.
Here in my following code you can noticed his undefined variable current_loggedin_user which I don't know how to get its value.
import graphene
from graphene_django import DjangoObjectType
from . import models
from django.conf import settings
class Posts(DjangoObjectType):
class Meta:
model = models.ExtendUser
if (current_logedin_user.id==1):
field = '__all_'
else:
fields = ['username', 'id', 'imageUrl']
You need to include all fields that are visible to anyone to the schema, and then customize the resolver methods for the fields that you want to hide for some users. For example:
class Posts(DjangoObjectType):
class Meta:
model = models.ExtendUser
def resolve_restricted_field(self, info):
if info.context.user.id == 1:
return self.restricted_field
return None
For more examples, see How to limit field access on a model based on user type on Graphene/Django?
Try something like this
class Posts(DjangoObjectType):
class Meta:
model = models.ExtendUser
class Query(ObjectType):
fields = graphene.List(Posts)
def resolve_fields(self, info, **kwargs):
if info.context.user.pk == 1:
return ExtendUser.objects.all()
return ExtendUser.objects.values_list('username', 'id', 'imageUrl', flat=True)

How to post data to Embedded document with Mongoengine REST

I am trying to use Django with mongoengine to make an API.
So far I can get the objects and delete them. but when I want to post some data. Lets say student + course it is giving an error:
type object 'Course' has no attribute 'objects'
Models en ..
#Model.py
class Course(EmbeddedDocument):
course_name = StringField(max_length=200)
course_fee = StringField(max_length=200)
class Student(Document):
student_name = StringField(max_length=200)
student_contactperson = StringField(max_length=200)
student_adress = StringField(max_length=200)
courses = ListField(EmbeddedDocumentField(Course))
#Serializers.py
class CourseSerializer(EmbeddedDocumentSerializer):
class Meta:
model = Course
fields = ('course_name','course_fee')
class StudentSerializer(DocumentSerializer):
courses = CourseSerializer(many=True)
class Meta:
model = Student
fields = ('student_name','student_contactperson','student_adress','courses')
depth = 2
def create(self, validated_data):
course_data = validated_data.pop('courses')
student = Student.objects.create(**validated_data)
Course.objects.create(student=student, **course_data)
return student
#Views.py
class StudentViewSet(meviewsets.ModelViewSet):
lookup_field = 'name'
queryset = Student.objects.all().order_by('-date_joined')
serializer_class = StudentSerializer
A Document represents a MongoDB document (i.e a record in a collection), a Document class is bound to a particular collection. An EmbeddedDocument represents a structure that gets nested in a Document.
So by design an EmbeddedDocument isn't attached to any collection unless you embed it inside a Document.
This means that you can't query or save an EmbeddedDocument class, you need to query/save the parent Document.
Document.objects is an entry point for querying a collection, it only exists on Document classes. You are calling Course.objects.create but Course is an EmbeddedDocument.
I believe you need to change your code to the following
class StudentSerializer(DocumentSerializer):
...
def create(self, validated_data):
course_data = validated_data.pop('courses')
course = Course(**course_data) # assuming course_data is {course_name: ..., course_fee: ...}
return Student.objects.create(courses=[course], **validated_data)

How to use a custom id with Graphene and Relay?

I've implemented graphql and I'm migrating to relay. I already have a uuid for every table and that is named 'id'. And my application I found this github thread that talks about possibly changing the spec but it feels like a rabbit hole.
Is there a simple way that I can use my own custom id with relay?
If you've already implemented a default relay endpoint then you should have some
TableNameNode classes that have a Meta nested class, and a seperate Query
class.
class ExampleTableNameNode(DjangoObjectType):
class Meta:
model = ExampleTableName
interface = (relay.Node,)
class Query(object):
example_table_name = relay.Node.Field(ExampleTableNameNode)
all_example_table_names = DjangoFilterConnectionField(ExampleTableNameNode)
def resolve_example_table_name(self, info, **kwargs):
pass
def resolve_all_example_table_names(self, info, **kwargs):
pass
The interface = (relay.Node,) is what defines:
How the ids are being generated
How they are used to fetch data
If we create a relay.Node subclass that redefines these two features then we can use our custom ids.
class CustomNode(relay.Node):
class Meta:
name = 'Node'
#staticmethod
def to_global_id(type, id):
#returns a non-encoded ID
return id
#staticmethod
def get_node_from_global_id(info, global_id, only_type=None):
model = getattr(Query,info.field_name).field_type._meta.model
return model.objects.get(id=global_id)
Here we implemented two functions, to_global_id, and get_node_from_global_id.
The line model = ... is a bit of magic to go from the graphql query table name
to the actual model. If that doesn't work you'll just need to make a dictionary
to go from something like example_table_name to the actual ExampleTableName
django model.
Once you do that you'll have to replace the two references to relay.Node with
CustomNode like so.
class ExampleTableNameNode(DjangoObjectType):
class Meta:
model = ExampleTableName
interface = (CustomNode,)
class Query(object):
example_table_name = CustomNode.Field(ExampleTableNameNode)
all_example_table_names = DjangoFilterConnectionField(ExampleTableNameNode)
def resolve_example_table_name(self, info, **kwargs):
pass
def resolve_all_example_table_names(self, info, **kwargs):
pass
The answer is in the graphene docs. I read them when I was implementing
graphene and relay but there is so much to learn at once that it's easy to read
through custom node section and not remember later that you need to do a custom
node solution.

How to limit the number of objects given from nested serialization

Store has a foreign key to SimilarStore. Normally, there is about a hundred of similar stores in similarstore_set. Is there a way to limit the number of similar stores in similarstore_set when I make API with Django REST Framework?
serializer.py
class SimilarStoreSerializer(ModelSerializer):
class Meta:
model = SimilarStore
fields = ('domain', )
class StoreSerializer(ModelSerializer):
similarstore_set = SimilarStoreSerializer(many=True)
class Meta:
model = Store
fields = '__all__'
UPDATE
The following codes throws 'Store' object has no attribute 'similarstores_set', it actually has similarstore_set, why is it throwing the error?
class StoreSerializer(ModelSerializer):
image_set = ImageSerializer(many=True)
promotion_set = PromotionSerializer(many=True)
similar_stores = SerializerMethodField()
def get_similar_stores(self, obj):
# get 10 similar stores for this store
stores = obj.similarstores_set.all()[:10] <-- This line throws the error
return SimilarStoreSerializer(stores, many=True).data
class Meta:
model = Store
fields = '__all__'
You can use a SerializerMethodField to perform a custom lookup and limit the number of records:
class StoreSerializer(ModelSerializer):
similar_stores = serializers.SerializerMethodField()
def get_similar_stores(self, obj):
stores = obj.similarstore_set.all()[:10] # get 10 similar stores for this store
return SimilarStoreSerializer(stores, many=True).data
class Meta:
model = Store
fields = '__all__'
You could add a serializers.SerializerMethodField() for similarstore_set and define a method that would query the SimilarStore data and set similarstore_set. You could pass the number of elements you want in similarstore_set by passing context to your serializer. see https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context

Resources