How to make HATEOAS render empty embedded array

和自甴很熟 提交于 2020-12-15 06:24:37

问题


Usually CollectionModel will return an _embedded array, but in this example:

@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");
    }

if the productMaterials is empty CollectionModel will not render the _embedded array which will break the client. Is there any ways to fix this?


回答1:


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);
        }
    }    


来源:https://stackoverflow.com/questions/64630041/how-to-make-hateoas-render-empty-embedded-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!