Skip to content

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

Fix graphql federation compatibility for ChannelContext (#7771)

Rafał Pitoń4ff346536bb4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f9e3295f82..b5c30933a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -153,6 +153,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add `customerId` to `checkoutCustomerAttach` mutation
- Add new permision `IMPERSONATE_USER`
+
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
- Drop deprecated meta mutations - #6422 by @maarcingebala
diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.py
index 7285862694..3de9d3462d 100644
--- a/saleor/graphql/account/resolvers.py
+++ b/saleor/graphql/account/resolvers.py
@@ -162,7 +162,7 @@ def resolve_address(info, id):
return models.Address.objects.filter(pk=address_pk).first()
if user and not user.is_anonymous:
return user.addresses.filter(id=address_pk).first()
- return PermissionDenied()
+ raise PermissionDenied()
def resolve_permissions(root: models.User):
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index 614894bd5d..8ec2756c42 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -5016,3 +5016,398 @@ def test_email_update_to_existing_email(user_api_client, customer_user, staff_us
"field": "newEmail",
}
]
+
+
+USER_FEDERATION_QUERY = """
+ query GetUserInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on User {
+ id
+ email
+ }
+ }
+ }
+"""
+
+
+def test_staff_query_user_by_id_for_federation(
+ staff_api_client, customer_user, permission_manage_users
+):
+ customer_user_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ },
+ ],
+ }
+
+ response = staff_api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ permissions=[permission_manage_users],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ "email": customer_user.email,
+ }
+ ]
+
+
+def test_staff_query_user_by_email_for_federation(
+ staff_api_client, customer_user, permission_manage_users
+):
+ customer_user_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "email": customer_user.email,
+ },
+ ],
+ }
+
+ response = staff_api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ permissions=[permission_manage_users],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ "email": customer_user.email,
+ }
+ ]
+
+
+def test_staff_query_user_by_id_without_permission_for_federation(
+ staff_api_client, customer_user
+):
+ customer_user_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ },
+ ],
+ }
+
+ response = staff_api_client.post_graphql(USER_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_staff_query_user_by_email_without_permission_for_federation(
+ staff_api_client, customer_user
+):
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "email": customer_user.email,
+ },
+ ],
+ }
+
+ response = staff_api_client.post_graphql(USER_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_customer_query_self_by_id_for_federation(user_api_client, customer_user):
+ customer_user_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ },
+ ],
+ }
+
+ response = user_api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ "email": customer_user.email,
+ }
+ ]
+
+
+def test_customer_query_self_by_email_for_federation(user_api_client, customer_user):
+ customer_user_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "email": customer_user.email,
+ },
+ ],
+ }
+
+ response = user_api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ "email": customer_user.email,
+ }
+ ]
+
+
+def test_customer_query_user_by_id_for_federation(
+ user_api_client, customer_user, staff_user
+):
+ staff_user_id = graphene.Node.to_global_id("User", staff_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "id": staff_user_id,
+ },
+ ],
+ }
+
+ response = user_api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_customer_query_user_by_email_for_federation(
+ user_api_client, customer_user, staff_user
+):
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "email": staff_user.email,
+ },
+ ],
+ }
+
+ response = user_api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_unauthenticated_query_user_by_id_for_federation(api_client, customer_user):
+ customer_user_id = graphene.Node.to_global_id("User", customer_user.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "id": customer_user_id,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_unauthenticated_query_user_by_email_for_federation(api_client, customer_user):
+ variables = {
+ "representations": [
+ {
+ "__typename": "User",
+ "email": customer_user.email,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(
+ USER_FEDERATION_QUERY,
+ variables,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+ADDRESS_FEDERATION_QUERY = """
+ query GetUserInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on Address {
+ id
+ city
+ }
+ }
+ }
+"""
+
+
+def test_customer_query_address_federation(user_api_client, customer_user, address):
+ customer_user.addresses.add(address)
+
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = user_api_client.post_graphql(ADDRESS_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ "city": address.city,
+ }
+ ]
+
+
+def test_customer_query_other_user_address_federation(
+ user_api_client, staff_user, customer_user, address
+):
+ staff_user.addresses.add(address)
+
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = user_api_client.post_graphql(ADDRESS_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_staff_query_other_user_address_federation(
+ staff_api_client, customer_user, address
+):
+ customer_user.addresses.add(address)
+
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = staff_api_client.post_graphql(ADDRESS_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_staff_query_other_user_address_with_permission_federation(
+ staff_api_client, customer_user, address, permission_manage_users
+):
+ customer_user.addresses.add(address)
+
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = staff_api_client.post_graphql(
+ ADDRESS_FEDERATION_QUERY,
+ variables,
+ permissions=[permission_manage_users],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_app_query_address_federation(app_api_client, address, permission_manage_users):
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = app_api_client.post_graphql(
+ ADDRESS_FEDERATION_QUERY,
+ variables,
+ permissions=[permission_manage_users],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ "city": address.city,
+ }
+ ]
+
+
+def test_app_no_permission_query_address_federation(app_api_client, address):
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = app_api_client.post_graphql(ADDRESS_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
+
+
+def test_unauthenticated_query_address_federation(api_client, address):
+ address_id = graphene.Node.to_global_id("Address", address.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Address",
+ "id": address_id,
+ },
+ ],
+ }
+
+ response = api_client.post_graphql(ADDRESS_FEDERATION_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [None]
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 449d5e2b72..2bb8bf5373 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -121,8 +121,13 @@ class Address(CountableDjangoObjectType):
return False
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
- return graphene.Node.get_node_from_global_id(_info, root.id)
+ def __resolve_reference(root: "Address", info, **_kwargs):
+ try:
+ from .resolvers import resolve_address
+
+ return resolve_address(info, root.id)
+ except PermissionDenied:
+ return None
class CustomerEvent(CountableDjangoObjectType):
@@ -373,10 +378,28 @@ class User(CountableDjangoObjectType):
return resolve_wishlist_items_from_user(root)
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
- if root.id is not None:
- return graphene.Node.get_node_from_global_id(_info, root.id)
- return get_user_model().objects.get(email=root.email)
+ def __resolve_reference(root: "User", info, **_kwargs):
+ User = get_user_model()
+
+ try:
+ if root.id is not None:
+ user = graphene.Node.get_node_from_global_id(info, root.id)
+ else:
+ user = get_user_model().objects.get(email=root.email)
+ except User.DoesNotExist:
+ user = None
+
+ if not user:
+ return None
+
+ auth_user = info.context.user
+ manage_staff = auth_user.has_perm(AccountPermissions.MANAGE_STAFF)
+ manage_users = auth_user.has_perm(AccountPermissions.MANAGE_USERS)
+
+ if user == auth_user or manage_staff or manage_users:
+ return user
+
+ return None
@staticmethod
def resolve_language_code(root, _info, **_kwargs):
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index d8b9f958e5..62e9d0a232 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -1,5 +1,3 @@
-from graphene_federation import build_schema
-
from ..graphql.notifications.schema import ExternalNotificationMutations
from .account.schema import AccountMutations, AccountQueries
from .app.schema import AppMutations, AppQueries
@@ -7,6 +5,7 @@ from .attribute.schema import AttributeMutations, AttributeQueries
from .channel.schema import ChannelMutations, ChannelQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
from .core.enums import unit_enums
+from .core.federation import build_federated_schema
from .core.schema import CoreMutations, CoreQueries
from .csv.schema import CsvMutations, CsvQueries
from .discount.schema import DiscountMutations, DiscountQueries
@@ -79,4 +78,4 @@ class Mutation(
pass
-schema = build_schema(Query, mutation=Mutation, types=unit_enums)
+schema = build_federated_schema(Query, mutation=Mutation, types=unit_enums)
diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.py
index b4273078d5..5f98970a72 100644
--- a/saleor/graphql/app/tests/queries/test_app.py
+++ b/saleor/graphql/app/tests/queries/test_app.py
@@ -270,3 +270,36 @@ def test_app_with_extensions_query(
assigned_permissions = [p.codename for p in app_extension.permissions.all()]
assigned_permissions = [{"code": p.upper()} for p in assigned_permissions]
assert assigned_permissions in returned_permission_codes
+
+
+def test_query_app_for_federation(api_client, app):
+ app_id = graphene.Node.to_global_id("App", app.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "App",
+ "id": app_id,
+ },
+ ],
+ }
+ query = """
+ query GetAppInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on App {
+ id
+ name
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "App",
+ "id": app_id,
+ "name": app.name,
+ }
+ ]
diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.py
index 58da71c111..0e195a082b 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -191,7 +191,7 @@ class App(CountableDjangoObjectType):
return root.tokens.all() # type: ignore
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
+ def __resolve_reference(root: "App", _info, **_kwargs):
return graphene.Node.get_node_from_global_id(_info, root.id)
@staticmethod
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index 27fa7b5829..4cf4b6bba6 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -1,4 +1,7 @@
+from typing import Union
+
import graphene
+from django.db.models import Model
from graphene.types.resolver import get_default_resolver
from graphene_django import DjangoObjectType
@@ -32,8 +35,13 @@ class ChannelContextType(DjangoObjectType):
return root.node.pk
@classmethod
- def is_type_of(cls, root: ChannelContext, info):
- return super().is_type_of(root.node, info)
+ def is_type_of(cls, root: Union[ChannelContext, Model], info):
+ # Unwrap node from ChannelContext if it didn't happen already
+ if isinstance(root, ChannelContext):
+ return super().is_type_of(root.node, info)
+
+ # Check type that was already unwrapped by the Entity union check
+ return super().is_type_of(root, info)
@staticmethod
def resolve_translation(root: ChannelContext, info, language_code):
diff --git a/saleor/graphql/core/federation.py b/saleor/graphql/core/federation.py
new file mode 100644
index 0000000000..fded59b998
--- /dev/null
+++ b/saleor/graphql/core/federation.py
@@ -0,0 +1,23 @@
+from graphene_federation import build_schema
+
+from ..channel import ChannelContext
+
+
+def build_federated_schema(query=None, mutation=None, **kwargs):
+ schema = build_schema(query, mutation, **kwargs)
+ set_entity_type_resolver(schema)
+ return schema
+
+
+def set_entity_type_resolver(schema):
+ """Set type resolver aware of ChannelContext on _Entity union."""
+ entity = schema.get_type("_Entity")
+ org_type_resolver = entity.resolve_type
+
+ def resolve_entity_type(instance, info):
+ if isinstance(instance, ChannelContext):
+ return org_type_resolver(instance.node, info)
+
+ return org_type_resolver(instance, info)
+
+ entity.resolve_type = resolve_entity_type
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index a65090aa1f..dbdd2a3433 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -1086,3 +1086,36 @@ def test_update_category_mutation_remove_background_image(
assert not data["backgroundImage"]
category_with_image.refresh_from_db()
assert not category_with_image.background_image
+
+
+def test_query_category_for_federation(api_client, non_default_category):
+ category_id = graphene.Node.to_global_id("Category", non_default_category.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Category",
+ "id": category_id,
+ },
+ ],
+ }
+ query = """
+ query GetCategoryInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on Category {
+ id
+ name
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Category",
+ "id": category_id,
+ "name": non_default_category.name,
+ }
+ ]
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index 83ce8e7664..d5b742e793 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -1406,3 +1406,37 @@ query Collections($sortBy: CollectionSortingInput) {
}
}
"""
+
+
+def test_query_collection_for_federation(api_client, published_collection, channel_USD):
+ collection_id = graphene.Node.to_global_id("Collection", published_collection.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Collection",
+ "id": collection_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+ query = """
+ query GetCollectionInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on Collection {
+ id
+ name
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Collection",
+ "id": collection_id,
+ "name": published_collection.name,
+ }
+ ]
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 56f8a12389..cbaf178e7e 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -10991,3 +10991,107 @@ def test_hidden_product_access_with_permission_manage_channels(
content = get_graphql_content(response)
total_count = content["data"]["products"]["totalCount"]
assert total_count == 2
+
+
+def test_query_product_for_federation(api_client, product, channel_USD):
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+ query = """
+ query GetProductInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on Product {
+ id
+ name
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "Product",
+ "id": product_id,
+ "name": product.name,
+ }
+ ]
+
+
+def test_query_product_media_for_federation(
+ api_client, product_with_image, channel_USD
+):
+ media = product_with_image.media.first()
+ media_id = graphene.Node.to_global_id("ProductMedia", media.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductMedia",
+ "id": media_id,
+ },
+ ],
+ }
+ query = """
+ query GetProductMediaInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on ProductMedia {
+ id
+ url
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "ProductMedia",
+ "id": media_id,
+ "url": "http://testserver/media/products/product.jpg",
+ }
+ ]
+
+
+def test_query_product_type_for_federation(api_client, product, channel_USD):
+ product_type = product.product_type
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductType",
+ "id": product_type_id,
+ },
+ ],
+ }
+ query = """
+ query GetProductTypeInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on ProductType {
+ id
+ name
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "ProductType",
+ "id": product_type_id,
+ "name": product_type.name,
+ }
+ ]
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 78284cc2fa..0297dcad14 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -4686,3 +4686,37 @@ def test_product_variant_stocks_delete_mutation_invalid_object_type_of_warehouse
assert len(errors) == 1
assert errors[0]["code"] == ProductErrorCode.GRAPHQL_ERROR.name
assert errors[0]["field"] == "warehouseIds"
+
+
+def test_query_product_variant_for_federation(api_client, variant, channel_USD):
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "representations": [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "channel": channel_USD.slug,
+ },
+ ],
+ }
+ query = """
+ query GetProductVariantInFederation($representations: [_Any]) {
+ _entities(representations: $representations) {
+ __typename
+ ... on ProductVariant {
+ id
+ name
+ }
+ }
+ }
+ """
+
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["_entities"] == [
+ {
+ "__typename": "ProductVariant",
+ "id": variant_id,
+ "name": variant.name,
+ }
+ ]
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index c6a98dec18..df7950c135 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -99,6 +99,11 @@ from ..dataloaders import (
)
from ..enums import ProductTypeKindEnum, VariantAttributeScope
from ..filters import ProductFilterInput
+from ..resolvers import (
+ resolve_collection_by_id,
+ resolve_product_by_id,
+ resolve_variant_by_id,
+)
from ..sorters import ProductOrder
from .channels import (
CollectionChannelListing,
@@ -172,8 +177,14 @@ class ProductPricingInfo(BasePricingInfo):
description = "Represents availability of a product in the storefront."
-@key(fields="id")
+@key(fields="id channel")
class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
+ channel = graphene.String(
+ description=(
+ "Channel given to retrieve this product variant. Also used by federation "
+ "gateway to resolve this object in a federated query."
+ ),
+ )
channel_listings = graphene.List(
graphene.NonNull(ProductVariantChannelListing),
description="List of price information in channels for the product.",
@@ -260,6 +271,10 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
interfaces = [relay.Node, ObjectWithMetadata]
model = models.ProductVariant
+ @staticmethod
+ def resolve_channel(root: ChannelContext[models.Product], info):
+ return root.channel_slug
+
@staticmethod
@one_of_permissions_required(
[ProductPermissions.MANAGE_PRODUCTS, OrderPermissions.MANAGE_ORDERS]
@@ -483,18 +498,36 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
return ImagesByProductVariantIdLoader(info.context).load(root.node.id)
@staticmethod
- def __resolve_reference(
- root: ChannelContext[models.ProductVariant], _info, **_kwargs
- ):
- return graphene.Node.get_node_from_global_id(_info, root.node.id)
+ def __resolve_reference(root: "ProductVariant", info, **_kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ has_required_permissions = has_one_of_permissions(
+ requestor, ALL_PRODUCTS_PERMISSIONS
+ )
+ _, id = from_global_id_or_error(root.id, ProductVariant)
+ variant = resolve_variant_by_id(
+ info,
+ id,
+ channel_slug=root.channel,
+ requestor=requestor,
+ requestor_has_access_to_all=has_required_permissions,
+ )
+ return (
+ ChannelContext(node=variant, channel_slug=root.channel) if variant else None
+ )
@staticmethod
def resolve_weight(root: ChannelContext[models.ProductVariant], _info, **_kwargs):
return convert_weight_to_default_weight_unit(root.node.weight)
-@key(fields="id")
+@key(fields="id channel")
class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
+ channel = graphene.String(
+ description=(
+ "Channel given to retrieve this product. Also used by federation "
+ "gateway to resolve this object in a federated query."
+ ),
+ )
description_json = graphene.JSONString(
description="Description of the product (JSON).",
deprecation_reason=(
@@ -591,6 +624,10 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
"rating",
]
+ @staticmethod
+ def resolve_channel(root: ChannelContext[models.Product], info):
+ return root.channel_slug
+
@staticmethod
def resolve_default_variant(root: ChannelContext[models.Product], info):
default_variant_id = root.node.default_variant_id
@@ -889,8 +926,15 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
)
@staticmethod
- def __resolve_reference(root: ChannelContext[models.Product], _info, **_kwargs):
- return graphene.Node.get_node_from_global_id(_info, root.node.id)
+ def __resolve_reference(root: "Product", info, **_kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ _, id = from_global_id_or_error(root.id, Product)
+ product = resolve_product_by_id(
+ info, id, channel_slug=root.channel, requestor=requestor
+ )
+ return (
+ ChannelContext(node=product, channel_slug=root.channel) if product else None
+ )
@staticmethod
def resolve_weight(root: ChannelContext[models.Product], _info, **_kwargs):
@@ -1034,7 +1078,7 @@ class ProductType(CountableDjangoObjectType):
return resolve_attributes(info, qs=qs, **kwargs)
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
+ def __resolve_reference(root: "ProductType", _info, **_kwargs):
return graphene.Node.get_node_from_global_id(_info, root.id)
@staticmethod
@@ -1042,8 +1086,14 @@ class ProductType(CountableDjangoObjectType):
return convert_weight_to_default_weight_unit(root.weight)
-@key(fields="id")
+@key(fields="id channel")
class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
+ channel = graphene.String(
+ description=(
+ "Channel given to retrieve this collection. Also used by federation "
+ "gateway to resolve this object in a federated query."
+ ),
+ )
description_json = graphene.JSONString(
description="Description of the collection (JSON).",
deprecation_reason=(
@@ -1083,6 +1133,10 @@ class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
interfaces = [relay.Node, ObjectWithMetadata]
model = models.Collection
+ @staticmethod
+ def resolve_channel(root: ChannelContext[models.Product], info):
+ return root.channel_slug
+
@staticmethod
def resolve_background_image(
root: ChannelContext[models.Collection], info, size=None, **_kwargs
@@ -1113,8 +1167,16 @@ class Collection(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
)
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
- return graphene.Node.get_node_from_global_id(_info, root.id)
+ def __resolve_reference(root: "Collection", info, **_kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ _type, id = from_global_id_or_error(root.id, Collection)
+ collection = resolve_collection_by_id(info, id, root.channel, requestor)
+
+ return (
+ ChannelContext(node=collection, channel_slug=root.channel)
+ if collection
+ else None
+ )
@staticmethod
def resolve_description_json(root: ChannelContext[models.Collection], info):
@@ -1220,7 +1282,7 @@ class Category(CountableDjangoObjectType):
return ChannelQsContext(qs=qs, channel_slug=channel)
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
+ def __resolve_reference(root: "Category", _info, **_kwargs):
return graphene.Node.get_node_from_global_id(_info, root.id)
@@ -1250,7 +1312,7 @@ class ProductMedia(CountableDjangoObjectType):
return info.context.build_absolute_uri(url)
@staticmethod
- def __resolve_reference(root, _info, **_kwargs):
+ def __resolve_reference(root: "ProductMedia", _info, **_kwargs):
return graphene.Node.get_node_from_global_id(_info, root.id)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7c72b0725d..e69026e75d 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1216,6 +1216,7 @@ type Collection implements Node & ObjectWithMetadata {
slug: String!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
+ channel: String
descriptionJson: JSONString @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `description` field instead.")
products(filter: ProductFilterInput, sortBy: ProductOrder, before: String, after: String, first: Int, last: Int): ProductCountableConnection
backgroundImage(size: Int): Image
@@ -5146,6 +5147,7 @@ type Product implements Node & ObjectWithMetadata {
rating: Float
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
+ channel: String
descriptionJson: JSONString @deprecated(reason: "This field will be removed in Saleor 4.0. Use the `description` field instead.")
thumbnail(size: Int): Image
pricing(address: AddressInput): ProductPricingInfo
@@ -5606,6 +5608,7 @@ type ProductVariant implements Node & ObjectWithMetadata {
weight: Weight
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
+ channel: String
channelListings: [ProductVariantChannelListing!]
pricing(address: AddressInput): VariantPricingInfo
attributes(variantSelection: VariantAttributeScope): [SelectedAttribute!]!