如何使 HATEOAS 渲染空嵌入数组

问题描述 投票:0回答:2

通常

CollectionModel
将返回一个
_embedded
数组,但在本例中:

@GetMapping("/{id}/productMaterials")
    public ResponseEntity<?> getProductMaterials(@PathVariable Integer id) {
        Optional<Material> optionalMaterial = materialRepository.findById(id);
        if (optionalMaterial.isPresent()) {
            List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
            CollectionModel<ProductMaterialModel> productMaterialModels =
                    new ProductMaterialModelAssembler(ProductMaterialController.class, ProductMaterialModel.class).
                            toCollectionModel(productMaterials);
            return ResponseEntity.ok().body(productMaterialModels);
        }
        return ResponseEntity.badRequest().body("no such material");
    }

如果

productMaterials
为空,
CollectionModel
将不会渲染
_embedded
数组,这会破坏客户端。有什么办法可以解决这个问题吗?

spring spring-boot spring-hateoas
2个回答
3
投票
if (optionalMaterial.isPresent()) {
        List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
        CollectionModel<ProductMaterialModel> productMaterialModels =
                new ProductMaterialModelAssembler(ProductMaterialController.class, ProductMaterialModel.class).
                        toCollectionModel(productMaterials);
        if(productMaterialModels.isEmpty()) {
            EmbeddedWrappers wrappers = new EmbeddedWrappers(false);
            EmbeddedWrapper wrapper = wrappers.emptyCollectionOf(ProductMaterialModel.class);
            Resources<Object> resources = new Resources<>(Arrays.asList(wrapper));
            return ResponseEntity.ok(new Resources<>(resources));
        } else {
            return ResponseEntity.ok().body(productMaterialModels);
        }
    }    

0
投票

现在使用此代码可以轻松完成:

    List<ProductMaterial> productMaterials = optionalMaterial.get().getProductMaterials();
    return HalModelBuilder.emptyHalModel()
            .embed(productMaterials, ProductMaterial.class)
            .build();
© www.soinside.com 2019 - 2024. All rights reserved.