如何使 HATEOAS 呈现空的嵌入式数组



通常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数组。有什么方法可以解决这个问题吗?

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

最新更新