51 lines
2.1 KiB
Java
51 lines
2.1 KiB
Java
package ch.dlmw.swisssignchallenge.controllers;
|
|
|
|
import ch.dlmw.swisssignchallenge.entities.SigningRequestDocument;
|
|
import ch.dlmw.swisssignchallenge.services.SigningRequestDocumentService;
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.github.fge.jsonpatch.JsonPatch;
|
|
import com.github.fge.jsonpatch.JsonPatchException;
|
|
import lombok.AllArgsConstructor;
|
|
import org.openapitools.api.SigningRequestDocumentApi;
|
|
import org.openapitools.model.PatchOperation;
|
|
import org.springframework.http.ResponseEntity;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
import java.io.IOException;
|
|
import java.util.List;
|
|
|
|
@RestController
|
|
@AllArgsConstructor
|
|
public class SigningRequestDocumentController implements SigningRequestDocumentApi {
|
|
private final SigningRequestDocumentService signingRequestDocumentService;
|
|
private final ObjectMapper objectMapper;
|
|
|
|
@Override
|
|
public ResponseEntity<Void> patchSigningRequestDocument(String id, List<PatchOperation> patchOperations) {
|
|
var document = signingRequestDocumentService.getSigningRequestDocument(id);
|
|
|
|
try {
|
|
var patchedDocument = applyPatch(patchOperations, document, SigningRequestDocument.class);
|
|
|
|
signingRequestDocumentService.updateSigningRequestDocument(patchedDocument);
|
|
|
|
return ResponseEntity.noContent().build();
|
|
} catch (JsonPatchException e) {
|
|
throw new IllegalArgumentException("Failed to apply patch", e);
|
|
} catch (IOException e) {
|
|
throw new RuntimeException("Failed to apply patch", e);
|
|
}
|
|
}
|
|
|
|
private <T> T applyPatch(List<PatchOperation> patchOperations, T object, Class<T> entityType) throws JsonPatchException, IOException {
|
|
JsonNode patchNode = objectMapper.valueToTree(patchOperations);
|
|
JsonPatch jsonPatch = JsonPatch.fromJson(patchNode);
|
|
|
|
JsonNode entityNode = objectMapper.convertValue(object, JsonNode.class);
|
|
JsonNode patchedNode = jsonPatch.apply(entityNode);
|
|
|
|
return objectMapper.treeToValue(patchedNode, entityType);
|
|
}
|
|
}
|