Skip to content

Commit

Permalink
35687 Change DinaRepositoryV2 create to use JsonApiDocument
Browse files Browse the repository at this point in the history
Changed create method, added customizer + improved checks in set relationships method
  • Loading branch information
cgendreau committed Feb 7, 2025
1 parent d3d5115 commit 9595bd9
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import lombok.NonNull;
Expand Down Expand Up @@ -507,15 +508,24 @@ private static int toSafePageLimit(Integer pageLimit) {

/**
* Create a new resource.
* Relationships are not supported at the moment.
* @param dto
* @param docToCreate
* @param dtoCustomizer used to customize the dto before being transformed to entity.
* Example, setting the authenticated user as createdBy. Can be null.
* @return the uuid assigned or used
*/
public UUID create(D dto) {
public UUID create(JsonApiDocument docToCreate, Consumer<D> dtoCustomizer) {

D dto = objMapper.convertValue(docToCreate.getAttributes(), resourceClass);
if(dtoCustomizer != null) {
dtoCustomizer.accept(dto);
}

E entity = dinaMapper.toEntity(dto,
registry.getAttributesPerClass().get(resourceClass),
null);

updateRelationships(entity, docToCreate.getRelationships());

authorizationService.authorizeCreate(entity);
E created = dinaService.create(entity);
return created.getUuid();
Expand Down Expand Up @@ -583,15 +593,25 @@ private void updateRelationships(E entity, Map<String, JsonApiDocument.Relations
List<Object> relationshipsReferences = new ArrayList<>();
for (Object el : relObject.getDataAsCollection()) {
var resourceIdentifier = toResourceIdentifier(el);
relationshipsReferences.add(
dinaService.getReferenceByNaturalId(relation.getEntityType(),
resourceIdentifier.getId()));
if (resourceIdentifier != null) {
relationshipsReferences.add(
dinaService.getReferenceByNaturalId(relation.getEntityType(),
resourceIdentifier.getId()));
} else {
log.warn("Can't convert to ResourceIdentifier list element, ignoring");
return;
}
}
relationshipsReference = relationshipsReferences;
} else { // to-one
var resourceIdentifier = toResourceIdentifier(relObject.getData());
relationshipsReference = dinaService.getReferenceByNaturalId(relation.getEntityType(),
resourceIdentifier.getId());
if (resourceIdentifier != null) {
relationshipsReference = dinaService.getReferenceByNaturalId(relation.getEntityType(),
resourceIdentifier.getId());
} else {
log.warn("Can't convert to ResourceIdentifier, ignoring");
return;
}
}
} else {
// remove relationship
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
Expand Down Expand Up @@ -50,7 +49,7 @@
properties = {"dev-user.enabled: true", "keycloak.enabled: false"},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(initializers = { PostgresTestContainerInitializer.class })
@Import({DinaRepositoryV2IT.TestDynaBeanRepo.class, DinaRepositoryV2IT.RepoV2TestConfig.class})
@Import({DinaRepositoryV2IT.TestDinaRepositoryV2.class, DinaRepositoryV2IT.RepoV2TestConfig.class})
public class DinaRepositoryV2IT extends BaseRestAssuredTest {

private static final String PATH = "repo2";
Expand Down Expand Up @@ -120,7 +119,7 @@ public void onPatchToManyRelationship() {
*/
@RestController
@RequestMapping(produces = JSON_API_VALUE)
static class TestDynaBeanRepo {
static class TestDinaRepositoryV2 {

@Getter
private Integer level;
Expand All @@ -133,15 +132,15 @@ static class TestDynaBeanRepo {

@PostMapping(PATH + "/" + TaskDTO.RESOURCE_TYPE)
@Transactional
public ResponseEntity<RepresentationModel<?>> handlePostTask(@RequestBody EntityModel<TaskDTO> taskDTO) {
taskRepo.create(taskDTO.getContent());
public ResponseEntity<RepresentationModel<?>> handlePostTask(@RequestBody JsonApiDocument doc) {
taskRepo.create(doc, (dto) -> dto.setUuid(doc.getId()));
return ResponseEntity.created(URI.create("/")).build();
}

@PostMapping(PATH + "/" + ProjectDTO.RESOURCE_TYPE)
@Transactional
public ResponseEntity<RepresentationModel<?>> handlePostProject(@RequestBody EntityModel<ProjectDTO> projectDTO) {
projectRepo.create(projectDTO.getContent());
public ResponseEntity<RepresentationModel<?>> handlePostProject(@RequestBody JsonApiDocument doc) {
projectRepo.create(doc, (dto) -> dto.setUuid(doc.getId()));
return ResponseEntity.created(URI.create("/")).build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
import ca.gc.aafc.dina.exception.ResourceNotFoundException;
import ca.gc.aafc.dina.filter.QueryComponent;
import ca.gc.aafc.dina.jsonapi.JsonApiDocument;
import ca.gc.aafc.dina.jsonapi.JsonApiDocuments;
import ca.gc.aafc.dina.mapper.PersonMapper;
import ca.gc.aafc.dina.security.auth.AllowAllAuthorizationService;
import ca.gc.aafc.dina.service.DinaService;
import ca.gc.aafc.dina.testsupport.PostgresTestContainerInitializer;
import ca.gc.aafc.dina.testsupport.jsonapi.JsonAPITestHelper;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
Expand Down Expand Up @@ -128,7 +130,9 @@ public void onCreateUpdateDelete_noException() throws ResourceNotFoundException
.name("Bob")
.build();

UUID assignedId = repositoryV2.create(personDto);
JsonApiDocument doc = JsonApiDocuments.createJsonApiDocument(null, PersonDTO.TYPE_NAME,
JsonAPITestHelper.toAttributeMap(personDto));
UUID assignedId = repositoryV2.create(doc, null);

Map<String, Object> attributes = new HashMap<>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ca.gc.aafc.dina.jsonapi;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
Expand All @@ -23,7 +24,6 @@ private JsonApiDocuments() {
*/
public static JsonApiDocument createJsonApiDocument(UUID uuid, String type,
Map<String, Object> attributes) {
Objects.requireNonNull(uuid);
Objects.requireNonNull(type);

return JsonApiDocument.builder()
Expand All @@ -36,6 +36,34 @@ public static JsonApiDocument createJsonApiDocument(UUID uuid, String type,
).build();
}

/**
* Creates a {@link JsonApiDocument} with to-one relationships for provided parameters.
* @param uuid
* @param type
* @param attributes
* @param relationships
* @return
*/
public static JsonApiDocument createJsonApiDocumentWithRelToOne(UUID uuid, String type,
Map<String, Object> attributes,
Map<String, JsonApiDocument.ResourceIdentifier> relationships) {
return createJsonApiDocument(uuid, type, attributes, relationships);
}

/**
* Creates a {@link JsonApiDocument} with to-many relationships for provided parameters.
* @param uuid
* @param type
* @param attributes
* @param relationships
* @return
*/
public static JsonApiDocument createJsonApiDocumentWithRelToMany(UUID uuid, String type,
Map<String, Object> attributes,
Map<String, List<JsonApiDocument.ResourceIdentifier>> relationships) {
return createJsonApiDocument(uuid, type, attributes, relationships);
}

/**
* Creates a {@link JsonApiDocument} with relationships for provided parameters
* @param uuid
Expand All @@ -46,8 +74,7 @@ public static JsonApiDocument createJsonApiDocument(UUID uuid, String type,
*/
public static JsonApiDocument createJsonApiDocument(UUID uuid, String type,
Map<String, Object> attributes,
Map<String, Object> relationships) {
Objects.requireNonNull(uuid);
Map<String, ?> relationships) {
Objects.requireNonNull(type);
Objects.requireNonNull(relationships);

Expand Down

0 comments on commit 9595bd9

Please sign in to comment.