From aef5dd51fc51fcbd23df8405c0332e0582bc6f58 Mon Sep 17 00:00:00 2001 From: Anthony LC Date: Thu, 20 Jun 2024 15:24:10 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F(backend)=20override=20docume?= =?UTF-8?q?nt=20perform=5Fcreate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We override the perform_create method of the DocumentViewSet to save the document with the id provided if a id is provided in the request. We do that because in offline mode we will create the document locally and we will need to save it with the id created locally to have our next requests to the server to be able to find the document with the id provided. --- src/backend/core/api/viewsets.py | 13 ++++++++++ .../documents/test_api_documents_create.py | 25 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/backend/core/api/viewsets.py b/src/backend/core/api/viewsets.py index 78b747b1..87c0de79 100644 --- a/src/backend/core/api/viewsets.py +++ b/src/backend/core/api/viewsets.py @@ -311,6 +311,19 @@ class DocumentViewSet( resource_field_name = "document" queryset = models.Document.objects.all() + def perform_create(self, serializer): + """ + Override perform_create to use the provided ID in the payload if it exists + """ + document_id = self.request.data.get("id") + document = serializer.save(id=document_id) if document_id else serializer.save() + + self.access_model_class.objects.create( + user=self.request.user, + role=models.RoleChoices.OWNER, + **{self.resource_field_name: document}, + ) + @decorators.action(detail=True, methods=["get"], url_path="versions") def versions_list(self, request, *args, **kwargs): """ diff --git a/src/backend/core/tests/documents/test_api_documents_create.py b/src/backend/core/tests/documents/test_api_documents_create.py index 58f7b667..c4bd11b1 100644 --- a/src/backend/core/tests/documents/test_api_documents_create.py +++ b/src/backend/core/tests/documents/test_api_documents_create.py @@ -1,6 +1,8 @@ """ Tests for Documents API endpoint in impress's core app: create """ +import uuid + import pytest from rest_framework.test import APIClient @@ -45,3 +47,26 @@ def test_api_documents_create_authenticated(): document = Document.objects.get() assert document.title == "my document" assert document.accesses.filter(role="owner", user=user).exists() + + +def test_api_documents_create_with_id_from_payload(): + """ + We should be able to create a document with an ID from the payload. + """ + user = factories.UserFactory() + + client = APIClient() + client.force_login(user) + + doc_id = uuid.uuid4() + response = client.post( + "/api/v1.0/documents/", + {"title": "my document", "id": str(doc_id)}, + format="json", + ) + + assert response.status_code == 201 + document = Document.objects.get() + assert document.title == "my document" + assert document.id == doc_id + assert document.accesses.filter(role="owner", user=user).exists()