Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Switch to using IDs

Marcin Gębala1ff128f92d95
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 4cdc86e143..86034d7e42 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -5,8 +5,11 @@ from graphene_django.filter import DjangoFilterConnectionField
from .core.filters import DistinctFilterSet
from .product.filters import ProductFilterSet
from .product.types import (
- Category, ProductAttribute, Product, resolve_attributes, resolve_products)
-from .product.mutations import CategoryMutation, CategoryDelete
+ Category, ProductAttribute, Product, resolve_attributes, resolve_products,
+ resolve_categories)
+from .product.mutations import (
+ CategoryCreateMutation, CategoryUpdateMutation, CategoryDelete)
+from .utils import get_node
class Query(graphene.ObjectType):
@@ -15,7 +18,8 @@ class Query(graphene.ObjectType):
filterset_class=DistinctFilterSet,
in_category=graphene.Argument(graphene.ID))
categories = DjangoFilterConnectionField(
- Category, filterset_class=DistinctFilterSet)
+ Category, filterset_class=DistinctFilterSet,
+ level=graphene.Argument(graphene.Int))
category = graphene.Field(Category, id=graphene.Argument(graphene.ID))
product = graphene.Field(Product, id=graphene.Argument(graphene.ID))
products = DjangoFilterConnectionField(
@@ -24,12 +28,13 @@ class Query(graphene.ObjectType):
debug = graphene.Field(DjangoDebug, name='__debug')
def resolve_category(self, info, id):
- return graphene.Node.get_node_from_global_id(
- info, id, only_type=Category)
+ return get_node(info, id, only_type=Category)
+
+ def resolve_categories(self, info, level=None):
+ return resolve_categories(info, level)
def resolve_product(self, info, id):
- return graphene.Node.get_node_from_global_id(
- info, id, only_type=Product)
+ return get_node(info, id, only_type=Product)
def resolve_products(self, info, **kwargs):
return resolve_products(info)
@@ -39,9 +44,9 @@ class Query(graphene.ObjectType):
class Mutations(graphene.ObjectType):
- category_create = CategoryMutation.Field()
+ category_create = CategoryCreateMutation.Field()
category_delete = CategoryDelete.Field()
- category_update = CategoryMutation.Field()
+ category_update = CategoryUpdateMutation.Field()
schema = graphene.Schema(Query, Mutations)
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index edcd10ed4a..49ef838be5 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -7,7 +7,10 @@ from graphene.types.mutation import MutationOptions
from graphene_django.form_converter import convert_form_field
from graphene_django.registry import get_global_registry
-from .types import ErrorType
+from ..utils import get_node
+from .types import Error
+
+registry = get_global_registry()
def fields_for_form(form_class):
@@ -18,16 +21,16 @@ def fields_for_form(form_class):
def convert_form_errors(form):
- """Convert ModelForm errors into a list of ErrorType objects."""
+ """Convert ModelForm errors into a list of Error objects."""
errors = []
for field in form.errors:
for message in form.errors[field]:
- errors.append(ErrorType(field=field, message=message))
+ errors.append(Error(field=field, message=message))
return errors
class BaseMutation(graphene.Mutation):
- errors = graphene.List(ErrorType)
+ errors = graphene.List(Error)
class Meta:
abstract = True
@@ -40,17 +43,19 @@ class ModelFormMutationOptions(MutationOptions):
class ModelFormMutation(BaseMutation):
+ class Meta:
+ abstract = True
+
@classmethod
def __init_subclass_with_meta__(
cls, arguments=None, form_class=None, return_field_name=None,
_meta=None, **options):
if not form_class:
raise ImproperlyConfigured(
- 'form_class are required for ModelMutation')
+ 'form_class are required for ModelFormMutation')
_meta = ModelFormMutationOptions(cls)
model = form_class._meta.model
- registry = get_global_registry()
model_type = registry.get_type_for_model(model)
if not return_field_name:
model_name = model.__name__
@@ -58,7 +63,6 @@ class ModelFormMutation(BaseMutation):
# get mutation arguments based on model form
arguments = fields_for_form(form_class)
- arguments['pk'] = graphene.Int()
# get mutation output field for model instance
fields = {return_field_name: graphene.Field(model_type)}
@@ -67,8 +71,7 @@ class ModelFormMutation(BaseMutation):
_meta.model = model
_meta.return_field_name = return_field_name
- super(ModelFormMutation, cls).__init_subclass_with_meta__(
- _meta=_meta, **options)
+ super().__init_subclass_with_meta__(_meta=_meta, **options)
# Update mutation's arguments and fields
cls._meta.arguments.update(arguments)
@@ -76,21 +79,12 @@ class ModelFormMutation(BaseMutation):
@classmethod
def get_form_kwargs(cls, root, info, **input):
- kwargs = {'data': input}
- pk = input.pop('pk', None)
- if pk:
- instance = cls._meta.model._default_manager.get(pk=pk)
- kwargs['instance'] = instance
- return kwargs
-
- @classmethod
- def get_form(cls, root, info, **kwargs):
- form_kwargs = cls.get_form_kwargs(root, info, **kwargs)
- return cls._meta.form_class(**form_kwargs)
+ return {'data': input}
@classmethod
def mutate(cls, root, info, **kwargs):
- form = cls.get_form(root, info, **kwargs)
+ form_kwargs = cls.get_form_kwargs(root, info, **kwargs)
+ form = cls._meta.form_class(**form_kwargs)
if form.is_valid():
instance = form.save()
kwargs = {cls._meta.return_field_name: instance}
@@ -98,3 +92,24 @@ class ModelFormMutation(BaseMutation):
else:
errors = convert_form_errors(form)
return cls(errors=errors)
+
+
+class ModelFormUpdateMutation(ModelFormMutation):
+
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def __init_subclass_with_meta__(cls, *args, **kwargs):
+ super().__init_subclass_with_meta__(cls, *args, **kwargs)
+ cls._meta.arguments.update({'id': graphene.ID()})
+
+ @classmethod
+ def get_form_kwargs(cls, root, info, **input):
+ kwargs = super().get_form_kwargs(root, info, **input)
+ id = input['id']
+ model = cls._meta.form_class._meta.model
+ model_type = registry.get_type_for_model(model)
+ instance = get_node(info, id, only_type=model_type)
+ kwargs['instance'] = instance
+ return kwargs
diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.py
index 192f35b58f..7a3b926072 100644
--- a/saleor/graphql/core/types.py
+++ b/saleor/graphql/core/types.py
@@ -28,7 +28,7 @@ class CountableDjangoObjectType(DjangoObjectType):
*args, connection=countable_conn, **kwargs)
-class ErrorType(graphene.ObjectType):
+class Error(graphene.ObjectType):
field = graphene.String()
message = graphene.String()
diff --git a/saleor/graphql/product/mutations.py b/saleor/graphql/product/mutations.py
index 3445ceead0..d42238c14a 100644
--- a/saleor/graphql/product/mutations.py
+++ b/saleor/graphql/product/mutations.py
@@ -1,35 +1,48 @@
import graphene
from ...dashboard.category.forms import CategoryForm
-from ...product.models import Category
-from ..core.mutations import BaseMutation, ModelFormMutation
-from ..utils import get_object_or_none
-from .types import CategoryType
+from ..core.mutations import BaseMutation, ModelFormMutation, ModelFormUpdateMutation
+from ..utils import get_node
+from .types import Category
-class CategoryMutation(ModelFormMutation):
+class CategoryCreateMutation(ModelFormMutation):
class Arguments:
- parent_pk = graphene.Int()
+ parent_id = graphene.ID()
class Meta:
form_class = CategoryForm
@classmethod
def get_form_kwargs(cls, root, info, **input):
- parent_pk = input.pop('parent_pk', None)
+ parent_id = input.pop('parent_id', None)
kwargs = super().get_form_kwargs(root, info, **input)
- kwargs['parent_pk'] = parent_pk
+ if parent_id:
+ parent = get_node(info, parent_id, only_type=Category)
+ else:
+ parent = None
+ kwargs['parent_pk'] = parent.pk if parent else None
+ return kwargs
+
+
+class CategoryUpdateMutation(ModelFormUpdateMutation):
+ class Meta:
+ form_class = CategoryForm
+
+ @classmethod
+ def get_form_kwargs(cls, root, info, **input):
+ kwargs = super().get_form_kwargs(root, info, **input)
+ kwargs['parent_pk'] = kwargs['instance'].parent_id
return kwargs
class CategoryDelete(BaseMutation):
- category = graphene.Field(CategoryType)
+ category = graphene.Field(Category)
class Arguments:
- pk = graphene.Int()
+ id = graphene.ID()
- def mutate(self, info, pk):
- category = get_object_or_none(Category, pk=pk)
- if category:
- category.delete()
+ def mutate(self, info, id):
+ category = get_node(info, id, only_type=Category)
+ category.delete()
return CategoryDelete(category=category)
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index f045e49680..3192178941 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -8,6 +8,7 @@ from ...product.templatetags.product_images import product_first_image
from ...product.utils import get_availability
from ..core.filters import DistinctFilterSet
from ..core.types import CountableDjangoObjectType, Price, PriceRange
+from ..utils import CategoryAncestorsCache, get_node
from .filters import ProductFilterSet
@@ -142,6 +143,28 @@ class ProductAttribute(CountableDjangoObjectType):
return self.values.all()
+def resolve_category(id, info):
+ categories = models.Category.tree.filter(id=id).get_cached_trees()
+ if categories:
+ category = categories[0]
+ cache = {CACHE_ANCESTORS: CategoryAncestorsCache(category)}
+ setattr(info.context, CONTEXT_CACHE_NAME, cache)
+ return category
+ return None
+
+
+def resolve_categories(info, level=None):
+ qs = models.Category.objects.all()
+ if level is not None:
+ qs = qs.filter(level=level)
+ return qs.distinct()
+
+
+def resolve_product(id, info):
+ products = models.Product.objects.available_products().filter(id=id)
+ return products.first()
+
+
def resolve_products(info):
return models.Product.objects.available_products().distinct()
@@ -151,8 +174,7 @@ def resolve_attributes(category_id, info):
if category_id:
# Get attributes that are used with product types
# within the given category.
- category = graphene.Node.get_node_from_global_id(
- info, category_id, only_type=Category)
+ category = get_node(info, category_id, only_type=Category)
if category is None:
return queryset.none()
tree = category.get_descendants(include_self=True)
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index 63e32654d0..45cff24ca0 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -1,5 +1,4 @@
import graphene
-from django.shortcuts import _get_queryset, get_object_or_404
class CategoryAncestorsCache:
@@ -19,31 +18,10 @@ class CategoryAncestorsCache:
return self._cache[category.level]
-class DjangoPkInterface(graphene.Interface):
- """Exposes the Django model primary key."""
-
- pk = graphene.ID(description="Primary key")
-
- def resolve_pk(self, info):
- return self.pk
-
-
-def get_object_or_none(klass, *args, **kwargs):
- """Return an object or None if the object was not found.
-
- klass may be a Model, Manager, or QuerySet object. All other passed
- arguments and keyword arguments are used in the get() query.
-
- This function is analogical to `django.shortcut.get_object_or_404`.
- """
- queryset = _get_queryset(klass)
- try:
- return queryset.get(*args, **kwargs)
- except AttributeError:
- klass__name = klass.__name__ if isinstance(
- klass, type) else klass.__class__.__name__
- raise ValueError(
- "First argument to get_object_or_none() must be a Model, Manager, "
- "or QuerySet, not '%s'." % klass__name)
- except queryset.model.DoesNotExist:
- return None
+def get_node(info, id, only_type=None):
+ node = graphene.Node.get_node_from_global_id(info, id, only_type=only_type)
+ print("NODE: ", node)
+ if not node:
+ raise Exception(
+ "Could not resolve to a node with the global id of '%s'." % id)
+ return node
diff --git a/tests/test_graphql.py b/tests/test_graphql.py
index c0170f3547..933258171d 100644
--- a/tests/test_graphql.py
+++ b/tests/test_graphql.py
@@ -5,7 +5,8 @@ import pytest
from django import forms
from saleor.dashboard.category.forms import CategoryForm
-from saleor.graphql.core.mutations import ModelFormMutation
+from saleor.graphql.core.mutations import (
+ ModelFormMutation, ModelFormUpdateMutation)
from saleor.product.models import Category, Product, ProductAttribute
@@ -36,14 +37,21 @@ def test_model_form_mutation():
assert 'test_input' in arguments
# check if model form field is present
assert 'name' in arguments
- # check if pk mean for updates is present
- assert 'pk' in arguments
output_fields = meta.fields
assert 'category' in output_fields
assert 'errors' in output_fields
+def test_model_form_update_mutation():
+ class CategoryUpdateMutation(ModelFormUpdateMutation):
+ class Meta:
+ form_class = CategoryForm
+
+ meta = CategoryUpdateMutation._meta
+ assert 'id' in meta.arguments
+
+
def get_content(response):
return json.loads(response.content.decode('utf8'))
@@ -464,19 +472,20 @@ def test_real_query(client, product_in_stock):
def test_category_create_mutation(client):
query = """
- mutation($name: String!, $description: String, $parent: Int) {
+ mutation($name: String!, $description: String, $parentId: ID) {
categoryCreate(
name: $name
description: $description
- parentPk: $parent
+ parentId: $parentId
) {
category {
- pk
+ id
name
slug
description
parent {
- pk
+ name
+ id
}
}
errors {
@@ -504,35 +513,33 @@ def test_category_create_mutation(client):
assert not data['category']['parent']
# test creating subcategory
- parent_pk = data['category']['pk']
+ parent_id = data['category']['id']
variables = json.dumps({
'name': category_name, 'description': category_description,
- 'parent': int(parent_pk)})
+ 'parentId': parent_id})
response = client.post(
'/graphql/', {'query': query, 'variables': variables})
content = get_content(response)
assert 'errors' not in content
data = content['data']['categoryCreate']
assert data['errors'] == []
- assert data['category']['parent']['pk'] == parent_pk
+ assert data['category']['parent']['id'] == parent_id
def test_category_update_mutation(client, default_category):
query = """
- mutation($pk: Int, $name: String!, $description: String, $parent: Int) {
+ mutation($id: ID, $name: String!, $description: String) {
categoryUpdate(
- pk: $pk
+ id: $id
name: $name
description: $description
- parentPk: $parent
) {
category {
- pk
+ id
name
- slug
description
parent {
- pk
+ id
}
}
errors {
@@ -542,33 +549,37 @@ def test_category_update_mutation(client, default_category):
}
}
"""
+ # create child category and test that the update mutation won't change
+ # it's parent
+ child_category = default_category.children.create(name='child')
category_name = 'Updated name'
category_description = 'Updated description'
- # test creating root category
+ category_id = graphene.Node.to_global_id('Category', child_category.pk)
variables = json.dumps({
'name': category_name, 'description': category_description,
- 'pk': default_category.pk})
+ 'id': category_id})
response = client.post(
'/graphql/', {'query': query, 'variables': variables})
content = get_content(response)
assert 'errors' not in content
data = content['data']['categoryUpdate']
assert data['errors'] == []
- assert data['category']['pk'] == str(default_category.pk)
+ assert data['category']['id'] == category_id
assert data['category']['name'] == category_name
assert data['category']['description'] == category_description
- assert not data['category']['parent']
+
+ parent_id = graphene.Node.to_global_id('Category', default_category.pk)
+ assert data['category']['parent']['id'] == parent_id
def test_category_delete_mutation(client, default_category):
query = """
- mutation($pk: Int) {
- categoryDelete(pk: $pk) {
+ mutation($id: ID!) {
+ categoryDelete(id: $id) {
category {
name
- pk
}
errors {
field
@@ -577,11 +588,13 @@ def test_category_delete_mutation(client, default_category):
}
}
"""
- variables = json.dumps({'pk': default_category.pk})
+ variables = json.dumps({
+ 'id': graphene.Node.to_global_id('Category', default_category.id)})
response = client.post(
'/graphql/', {'query': query, 'variables': variables})
content = get_content(response)
assert 'errors' not in content
data = content['data']['categoryDelete']
- assert data['category']['pk'] is None
assert data['category']['name'] == default_category.name
+ with pytest.raises(Category.DoesNotExist):
+ default_category.refresh_from_db()