Skip to content

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

Add generic FileUpload mutation (#6470)

Iga Karbowiaka34362f7caa2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 305b7d3ea8..09e70af1ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Migrate draftjs content to editorjs format - #6430 by @IKarbowiak
- Drop deprecated service accounts and webhooks API - #6431 by @maarcingebala
- Add editorjs sanitizer - #6456 by @IKarbowiak
+- Add generic FileUpload mutation - #6470 by @IKarbowiak
# 2.11.1
diff --git a/saleor/core/error_codes.py b/saleor/core/error_codes.py
index 28790bf9cb..eae887dd9e 100644
--- a/saleor/core/error_codes.py
+++ b/saleor/core/error_codes.py
@@ -22,3 +22,7 @@ class TranslationErrorCode(Enum):
GRAPHQL_ERROR = "graphql_error"
NOT_FOUND = "not_found"
REQUIRED = "required"
+
+
+class UploadErrorCode(Enum):
+ GRAPHQL_ERROR = "graphql_error"
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 46c983a291..40a3a0caa5 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -3,7 +3,7 @@ from graphene_federation import build_schema
from .account.schema import AccountMutations, AccountQueries
from .app.schema import AppMutations, AppQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
-from .core.schema import CoreQueries
+from .core.schema import CoreMutations, CoreQueries
from .csv.schema import CsvMutations, CsvQueries
from .discount.schema import DiscountMutations, DiscountQueries
from .giftcard.schema import GiftCardMutations, GiftCardQueries
@@ -50,6 +50,7 @@ class Mutation(
AccountMutations,
AppMutations,
CheckoutMutations,
+ CoreMutations,
CsvMutations,
DiscountMutations,
PluginsMutations,
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 8046ea0ca5..ac510ba5a6 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -105,6 +105,7 @@ ProductErrorCode = graphene.Enum.from_enum(product_error_codes.ProductErrorCode)
ShopErrorCode = graphene.Enum.from_enum(core_error_codes.ShopErrorCode)
ShippingErrorCode = graphene.Enum.from_enum(shipping_error_codes.ShippingErrorCode)
StockErrorCode = graphene.Enum.from_enum(warehouse_error_codes.StockErrorCode)
+UploadErrorCode = graphene.Enum.from_enum(core_error_codes.UploadErrorCode)
WarehouseErrorCode = graphene.Enum.from_enum(warehouse_error_codes.WarehouseErrorCode)
WebhookErrorCode = graphene.Enum.from_enum(webhook_error_codes.WebhookErrorCode)
WishlistErrorCode = graphene.Enum.from_enum(wishlist_error_codes.WishlistErrorCode)
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index d327872384..fe6a1f2f23 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -7,6 +7,7 @@ from django.core.exceptions import (
ImproperlyConfigured,
ValidationError,
)
+from django.core.files.storage import default_storage
from django.db.models.fields.files import FileField
from graphene import ObjectType
from graphene.types.mutation import MutationOptions
@@ -15,8 +16,10 @@ from graphql.error import GraphQLError
from ...core.exceptions import PermissionDenied
from ...core.permissions import AccountPermissions
+from ..decorators import staff_member_or_app_required
from ..utils import get_nodes
-from .types import Error, Upload
+from .types import Error, Upload, UploadedFile
+from .types.common import UploadError
from .utils import from_global_id_strict_type, snake_to_camel_case
from .utils.error_codes import get_error_code_from_error
@@ -618,3 +621,31 @@ class ModelBulkDeleteMutation(BaseBulkMutation):
@classmethod
def bulk_action(cls, queryset):
queryset.delete()
+
+
+class FileUpload(BaseMutation):
+ uploaded_file = graphene.Field(UploadedFile)
+
+ class Arguments:
+ file = Upload(
+ required=True, description="Represents a file in a multipart request."
+ )
+
+ class Meta:
+ description = (
+ "Upload a file. This mutation must be sent as a `multipart` "
+ "request. More detailed specs of the upload format can be found here: "
+ "https://github.com/jaydenseric/graphql-multipart-request-spec"
+ )
+ error_type_class = UploadError
+ error_type_field = "upload_errors"
+
+ @classmethod
+ @staff_member_or_app_required
+ def perform_mutation(cls, _root, info, **data):
+ file_data = info.context.FILES.get(data["file"])
+ path = default_storage.save(file_data._name, file_data.file)
+
+ return FileUpload(
+ uploaded_file=UploadedFile(url=path, content_type=file_data.content_type)
+ )
diff --git a/saleor/graphql/core/schema.py b/saleor/graphql/core/schema.py
index 509381b285..d89a11a018 100644
--- a/saleor/graphql/core/schema.py
+++ b/saleor/graphql/core/schema.py
@@ -1,5 +1,6 @@
import graphene
+from .mutations import FileUpload
from .types.common import TaxType
@@ -14,3 +15,7 @@ class CoreQueries(graphene.ObjectType):
TaxType(description=tax.description, tax_code=tax.code)
for tax in manager.get_tax_rate_type_choices()
]
+
+
+class CoreMutations(graphene.ObjectType):
+ file_upload = FileUpload.Field()
diff --git a/saleor/graphql/core/tests/test_file_upload.py b/saleor/graphql/core/tests/test_file_upload.py
new file mode 100644
index 0000000000..51ea405385
--- /dev/null
+++ b/saleor/graphql/core/tests/test_file_upload.py
@@ -0,0 +1,106 @@
+from django.core.files.storage import default_storage
+
+from ....product.tests.utils import create_image
+from ...tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_multipart_request_body,
+)
+
+FILE_UPLOAD_MUTATION = """
+mutation fileUpload($file: Upload!) {
+ fileUpload(file: $file) {
+ uploadedFile {
+ url
+ contentType
+ }
+ uploadErrors {
+ code
+ }
+ }
+}
+"""
+
+
+def test_file_upload_by_staff(staff_api_client, media_root):
+ # given
+ image_file, image_name = create_image()
+ variables = {"image": image_name}
+ body = get_multipart_request_body(
+ FILE_UPLOAD_MUTATION, variables, image_file, image_name
+ )
+
+ # when
+ response = staff_api_client.post_multipart(body)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["fileUpload"]
+ errors = data["uploadErrors"]
+
+ expected_path = image_file._name
+ assert not errors
+ assert data["uploadedFile"]["contentType"] == "image/png"
+ assert data["uploadedFile"]["url"] == expected_path
+ assert default_storage.exists(expected_path)
+
+
+def test_file_upload_by_customer(user_api_client, media_root):
+ # given
+ image_file, image_name = create_image()
+ variables = {"image": image_name}
+ body = get_multipart_request_body(
+ FILE_UPLOAD_MUTATION, variables, image_file, image_name
+ )
+
+ # when
+ response = user_api_client.post_multipart(body)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_file_upload_by_app(app_api_client, media_root):
+ # given
+ image_file, image_name = create_image()
+ variables = {"image": image_name}
+ body = get_multipart_request_body(
+ FILE_UPLOAD_MUTATION, variables, image_file, image_name
+ )
+
+ # when
+ response = app_api_client.post_multipart(body)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["fileUpload"]
+ errors = data["uploadErrors"]
+
+ expected_path = image_file._name
+ assert not errors
+ assert data["uploadedFile"]["contentType"] == "image/png"
+ assert data["uploadedFile"]["url"] == expected_path
+ assert default_storage.exists(expected_path)
+
+
+def test_file_upload_by_superuser(superuser_api_client, media_root):
+ # given
+ image_file, image_name = create_image()
+ variables = {"image": image_name}
+ body = get_multipart_request_body(
+ FILE_UPLOAD_MUTATION, variables, image_file, image_name
+ )
+
+ # when
+ response = superuser_api_client.post_multipart(body)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["fileUpload"]
+ errors = data["uploadErrors"]
+
+ expected_path = image_file._name
+ assert not errors
+ assert data["uploadedFile"]["contentType"] == "image/png"
+ assert data["uploadedFile"]["url"] == expected_path
+ assert default_storage.exists(expected_path)
diff --git a/saleor/graphql/core/types/__init__.py b/saleor/graphql/core/types/__init__.py
index 41ce737ac2..6fae71dda0 100644
--- a/saleor/graphql/core/types/__init__.py
+++ b/saleor/graphql/core/types/__init__.py
@@ -7,6 +7,7 @@ from .common import (
Permission,
SeoInput,
TaxType,
+ UploadedFile,
Weight,
)
from .filter_input import FilterInputObjectType
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 18f3ad73e7..ca1a3ea04e 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -24,6 +24,7 @@ from ..enums import (
ShopErrorCode,
StockErrorCode,
TranslationErrorCode,
+ UploadErrorCode,
WarehouseErrorCode,
WebhookErrorCode,
WeightUnitsEnum,
@@ -212,6 +213,10 @@ class BulkStockError(ProductError):
)
+class UploadError(Error):
+ code = UploadErrorCode(description="The error code.", required=True)
+
+
class WarehouseError(Error):
code = WarehouseErrorCode(description="The error code.", required=True)
@@ -264,6 +269,13 @@ class Image(graphene.ObjectType):
return Image(url, alt)
+class UploadedFile(graphene.ObjectType):
+ url = graphene.String(required=True, description="The URL of the uploaded file.")
+ content_type = graphene.String(
+ required=True, description="Content type of uploaded file."
+ )
+
+
class PriceRangeInput(graphene.InputObjectType):
gte = graphene.Float(description="Price greater than or equal to.", required=False)
lte = graphene.Float(description="Price less than or equal to.", required=False)
diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.py
index b9d3e64e7a..e838cc55b5 100644
--- a/saleor/graphql/core/utils/error_codes.py
+++ b/saleor/graphql/core/utils/error_codes.py
@@ -3,7 +3,12 @@ from enum import Enum
from ....account.error_codes import AccountErrorCode, PermissionGroupErrorCode
from ....app.error_codes import AppErrorCode
from ....checkout.error_codes import CheckoutErrorCode
-from ....core.error_codes import MetadataErrorCode, ShopErrorCode, TranslationErrorCode
+from ....core.error_codes import (
+ MetadataErrorCode,
+ ShopErrorCode,
+ TranslationErrorCode,
+ UploadErrorCode,
+)
from ....csv.error_codes import ExportErrorCode
from ....discount.error_codes import DiscountErrorCode
from ....giftcard.error_codes import GiftCardErrorCode
@@ -61,6 +66,7 @@ SALEOR_ERROR_CODE_ENUMS = [
ShippingErrorCode,
ShopErrorCode,
TranslationErrorCode,
+ UploadErrorCode,
]
saleor_error_codes = []
diff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.py
index 759594a7ec..ef4bedf70e 100644
--- a/saleor/graphql/decorators.py
+++ b/saleor/graphql/decorators.py
@@ -72,3 +72,8 @@ def one_of_permissions_required(perms: Iterable[Enum]):
staff_member_required = account_passes_test(
lambda context: context.user.is_active and context.user.is_staff
)
+
+
+staff_member_or_app_required = account_passes_test(
+ lambda context: context.app or (context.user.is_active and context.user.is_staff)
+)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index e654d07df4..00264dfca8 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1837,6 +1837,12 @@ enum FileTypesEnum {
XLSX
}
+type FileUpload {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ uploadedFile: UploadedFile
+ uploadErrors: [UploadError!]!
+}
+
type Fulfillment implements Node & ObjectWithMetadata {
id: ID!
fulfillmentOrder: Int!
@@ -2571,6 +2577,7 @@ type Mutation {
voucherCataloguesRemove(id: ID!, input: CatalogueInput!): VoucherRemoveCatalogues
voucherTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): VoucherTranslate
exportProducts(input: ExportProductsInput!): ExportProducts
+ fileUpload(file: Upload!): FileUpload
checkoutAddPromoCode(checkoutId: ID!, promoCode: String!): CheckoutAddPromoCode
checkoutBillingAddressUpdate(billingAddress: AddressInput!, checkoutId: ID!): CheckoutBillingAddressUpdate
checkoutComplete(checkoutId: ID!, paymentData: JSONString, redirectUrl: String, storeSource: Boolean = false): CheckoutComplete
@@ -4765,6 +4772,21 @@ type UpdatePrivateMetadata {
scalar Upload
+type UploadError {
+ field: String
+ message: String
+ code: UploadErrorCode!
+}
+
+enum UploadErrorCode {
+ GRAPHQL_ERROR
+}
+
+type UploadedFile {
+ url: String!
+ contentType: String!
+}
+
type User implements Node & ObjectWithMetadata {
id: ID!
lastLogin: DateTime