gpt4 book ai didi

java - WebFlux 条件平面图

转载 作者:行者123 更新时间:2023-12-05 02:59:41 25 4
gpt4 key购买 nike

我对 webflux 比较陌生,我想找到解决方案来避免在有条件时嵌套 flatMap:

我有 3 个简单的实体:

项目、品牌、类别。

Item基本包含:brandId和categoryId

public Mono<Item> patch(String itemId, PatchSpecs specs) {
return itemRepository.findById(itemId)
.switchIfEmpty(Mono.error(..)))
.flatMap(item -> {
final String brandId = specs.getBrandId();
if (brandId != null) {
return brandService.getById(brandId)
.switchIfEmpty(Mono.error(..)))
.flatMap(brand -> {
final String categoryId = specs.getCategoryId();
if (categoryId != null) {
return categoryService.getById(categoryId)... -> return updateAndSave(..)
}
return updateAndSave(specs, item, brand, null);
});
}
else {
final String categoryId = specs.getCategoryId();
if (categoryId != null) {
return categoryService.getById(categoryId)... -> return updateAndSave(..)
}
return updateAndSave(specs, item, null, null);
}

});
}

如何防止这种分支条件 flatMaps 困惑?我无法想象如果我在项目中有另一个实体。会有更多嵌套的flatMap吗?

最佳答案

如果我很好地理解您的代码,类别和品牌是商品的可选属性。在这种情况下,我建议如下:

public Mono<Item> patch(String itemId, PatchSpecs specs)
{
return itemRepository.findById(itemId)
.switchIfEmpty(Mono.error(new RuntimeException("Can not find item.")))
.flatMap(item -> updateAndSave(specs, item));
}

private Mono<? extends Item> updateAndSave(PatchSpecs specs, Item item)
{
Mono<Optional<Brand>> brand = getBrand(specs.getBrandId());
Mono<Optional<Category>> category = getCategory(specs.getCategoryId());

return Mono.zip(Mono.just(item), brand, category)
.flatMap(tuple -> updateAndSave(specs, tuple));
}

private Mono<Optional<Brand>> getBrand(String inputBrandId)
{
return Mono.justOrEmpty(inputBrandId)
.flatMap(brandId -> brandService.getById(brandId)
.switchIfEmpty(Mono.error(new RuntimeException("Can not find brand."))))
.map(Optional::of)
.defaultIfEmpty(Optional.empty());
}

private Mono<Optional<Category>> getCategory(String inputCategoryId)
{
return Mono.justOrEmpty(inputCategoryId)
.flatMap(brandId -> categoryService.getById(brandId)
.switchIfEmpty(Mono.error(new RuntimeException("Can not find brand."))))
.map(Optional::of)
.defaultIfEmpty(Optional.empty());
}

private Mono<Item> updateAndSave(PatchSpecs specs, Tuple3<Item, Optional<Brand>, Optional<Category>> tuple)
{
Item item = tuple.getT1();
Brand brand = tuple.getT2().orElse(null);
Category category = tuple.getT3().orElse(null);

// TODO do update and save here
return null;
}

这样扩展性更好,不需要重复和嵌套条件。请验证它是否按预期工作。

关于java - WebFlux 条件平面图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57635069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com