Skip to content

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

WIP Improve category mutations

Marcin Gębalad1e6a20a7417
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 0ecd330820..16d00d90ea 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -2,11 +2,11 @@ import graphene
from graphene_django.debug import DjangoDebug
from graphene_django.filter import DjangoFilterConnectionField
-from .product.types import (
- Category, ProductAttribute, Product, resolve_attributes,
- resolve_products)
from .core.filters import DistinctFilterSet
from .product.filters import ProductFilterSet
+from .product.mutations import CategoryCreate, CategoryDelete, CategoryUpdate
+from .product.types import (
+ Category, Product, ProductAttribute, resolve_attributes, resolve_products)
class Query(graphene.ObjectType):
diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.py
index bc2230fb69..192f35b58f 100644
--- a/saleor/graphql/core/types.py
+++ b/saleor/graphql/core/types.py
@@ -28,6 +28,11 @@ class CountableDjangoObjectType(DjangoObjectType):
*args, connection=countable_conn, **kwargs)
+class ErrorType(graphene.ObjectType):
+ field = graphene.String()
+ message = graphene.String()
+
+
class Price(graphene.ObjectType):
currency = graphene.String()
gross = graphene.Float()
diff --git a/saleor/graphql/product/mutations.py b/saleor/graphql/product/mutations.py
index 27a040a74b..cafd93777a 100644
--- a/saleor/graphql/product/mutations.py
+++ b/saleor/graphql/product/mutations.py
@@ -1,73 +1,74 @@
import graphene
+from django.shortcuts import get_object_or_404
from ...dashboard.category.forms import CategoryForm
from ...product.models import Category
-from .types import CategoryType
+from ..utils import get_object_or_none
+from .types import CategoryType, ErrorType
-class Mutation(graphene.Mutation):
- errors = graphene.List(graphene.String)
+def convert_form_errors(form):
+ """Convert ModelForm errors into a list of ErrorType objects"""
+ errors = []
+ for field in form.errors:
+ for message in form.errors[field]:
+ errors.append(ErrorType(field=field, message=message))
+ return errors
+
+
+class CategoryMutation(graphene.Mutation):
+ category = graphene.Field(CategoryType)
+ errors = graphene.List(ErrorType)
def mutate(self, info):
raise NotImplementedError
-class CategoryCreateInput(graphene.InputObjectType):
+class CategoryInput(graphene.InputObjectType):
name = graphene.String()
description = graphene.String()
parent = graphene.Int()
-class CategoryCreate(Mutation):
- category = graphene.Field(CategoryType)
-
+class CategoryCreate(CategoryMutation):
class Arguments:
- input = CategoryCreateInput()
+ data = CategoryInput()
- def mutate(self, info, input):
+ def mutate(self, info, data):
category = Category()
- form = CategoryForm(input, instance=category, parent_pk=input.parent)
+ errors = []
+ form = CategoryForm(data, instance=category, parent_pk=data.parent)
if form.is_valid():
category = form.save()
- errors = []
else:
- errors = form.errors
+ errors = convert_form_errors(form)
return CategoryCreate(category=category, errors=errors)
-class CategoryUpdate(Mutation):
- category = graphene.Field(CategoryType)
-
+class CategoryUpdate(CategoryMutation):
class Arguments:
- input = CategoryCreateInput()
+ data = CategoryInput()
pk = graphene.Int()
- def mutate(self, info, input, pk):
- try:
- category = Category.objects.get(pk=pk)
- except Category.DoesNotExist:
- errors = ['not-found']
- category = None
- else:
- form = CategoryForm(input, instance=category, parent_pk=input.parent)
+ def mutate(self, info, data, pk):
+ category = get_object_or_none(Category, pk=pk)
+ errors = []
+ if category:
+ form = CategoryForm(
+ data, instance=category, parent_pk=category.parent_id)
if form.is_valid():
category = form.save()
- errors = []
else:
- errors = form.errors
- return CategoryUpdate(category=category, errors=errors)
+ errors = convert_form_errors(form)
+ return CategoryCreate(category=category, errors=errors)
-class CategoryDelete(Mutation):
+class CategoryDelete(CategoryMutation):
class Arguments:
pk = graphene.Int()
def mutate(self, info, pk):
- try:
- category = Category.objects.get(pk=pk)
- except Category.DoesNotExist:
- errors = ['not-found']
- else:
+ category = get_object_or_none(Category, pk=pk)
+ if category:
category.delete()
- errors = []
- return CategoryDelete(errors=errors)
+ return CategoryCreate(category=category)
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
new file mode 100644
index 0000000000..63e32654d0
--- /dev/null
+++ b/saleor/graphql/utils.py
@@ -0,0 +1,49 @@
+import graphene
+from django.shortcuts import _get_queryset, get_object_or_404
+
+
+class CategoryAncestorsCache:
+ """Cache used to store ancestors of a category in GraphQL context.
+
+ Allows to reduce the number of database queries. Categories of the same
+ tree depth level have common ancestors, which allows us to cache them by
+ the level.
+ """
+
+ def __init__(self, category):
+ self._cache = {category.level: category.get_ancestors()}
+
+ def get(self, category):
+ if category.level not in self._cache:
+ self._cache[category.level] = category.get_ancestors()
+ 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