Skip to content

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

Add function get_nodes

akjanik76d859dae889
diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.py
index 050794b866..e99b8e67f6 100644
--- a/saleor/graphql/utils.py
+++ b/saleor/graphql/utils.py
@@ -1,6 +1,7 @@
import graphene
from django.utils.encoding import smart_text
from django.utils.text import slugify
+from graphql_relay import from_global_id
from ..product.models import AttributeChoiceValue, ProductAttribute
@@ -14,6 +15,17 @@ def get_node(info, id, only_type=None):
return node
+def get_nodes(ids, graphene_type):
+ """Return list of nodes of proper type."""
+ pks = []
+ for graphql_id in ids:
+ _type, _id = from_global_id(graphql_id)
+ assert str(graphene_type) == _type, (
+ 'Must receive an {} id.').format(graphene_type._meta.name)
+ pks.append(_id)
+ return list(graphene_type._meta.model.objects.filter(pk__in=pks))
+
+
def get_attributes_dict_from_list(attributes, attr_slug_id):
"""
:param attributes: list
diff --git a/tests/api/test_graphql.py b/tests/api/test_graphql.py
index 9db8ec2d39..6eefc266b6 100644
--- a/tests/api/test_graphql.py
+++ b/tests/api/test_graphql.py
@@ -1,17 +1,21 @@
import json
-from unittest.mock import patch
+from unittest.mock import Mock, patch
import graphene
+import pytest
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponse
from django.shortcuts import reverse
from django.test import RequestFactory
from graphql_jwt.shortcuts import get_token
+from graphql_relay import to_global_id
from tests.utils import get_graphql_content
from saleor.graphql.core.mutations import (
ModelFormMutation, ModelFormUpdateMutation)
from saleor.graphql.middleware import jwt_middleware
+from saleor.graphql.product.types import Product
+from saleor.graphql.utils import get_nodes
def test_jwt_middleware(admin_client, admin_user):
@@ -230,3 +234,16 @@ def test_model_form_update_mutation(model_form_class):
meta = TestUpdateMutation._meta
assert 'id' in meta.arguments
+
+def test_get_nodes(product_list):
+ global_ids = [to_global_id('Product', product.pk) for product in product_list]
+ # Return products corresponding to global ids
+ products = get_nodes(global_ids, Product)
+ assert products == product_list
+
+ # Raise an error if one of the node is of wrong type
+ invalid_item = Mock(type='test', pk=123)
+ invalid_item_global_id = to_global_id(invalid_item.type, invalid_item.pk)
+ global_ids.append(invalid_item_global_id)
+ with pytest.raises(AssertionError):
+ get_nodes(global_ids, Product)