我正在创建一个API,它应该获取不是fork的存储库,并为每个存储库获取一个分支列表。但是,我有一个问题,因为:
1.我不知道如何在Web客户端中过滤响应以检查仓库是否是fork。我应该将webClient响应分配给一个变量,然后进行筛选吗?
1.我不知道如何从Mono<Branch[]>中提取分支[]来创建ResponseRepo。
我已经用RestTemplate做到了这一点,但我想用WebClient以非阻塞的方式做到这一点。
回购记录public record Repo(String name, Owner owner, Boolean fork) {}
分支记录public record Branch(String name, Commit commit) {}
ResponseRepo记录public record ResponseRepo(String name, String ownerLogin, Branch[] branches) {}
@Service
public class RepoServiceImpl implements RepoService {
private final WebClient webClient;
public RepoServiceImpl(WebClient.Builder builder) {
this.webClient = builder.baseUrl("https://api.github.com").build();
}
public Flux<ResponseRepo> getReposInfo(String username) {
return getRepos(username)
.flatMap(repo -> {
String name = repo.name();
String ownerLogin = repo.owner().login();
Mono<Branch[]> branches = getBranches(username, repo.name());
return new ResponseRepo(name, ownerLogin, branches);
})
}
private Flux<Repo> getRepos(String username) {
return webClient
.get()
.uri("/users/" + username + "/repos")
.retrieve()
.bodyToFlux(Repo.class);
}
private Mono<Branch[]> getBranches(String username, String repo) {
return webClient
.get()
.uri("/repos/" + username + "/" + repo + "/branches")
.retrieve()
.bodyToMono(Branch[].class);
}
}
在这里,我想从Mono<Branch[]>中获取分支[],以创建ResponseRepo
这是我的招聘任务,所以也许它会帮助别人。
1条答案
按热度按时间vbkedwbf1#
从您的代码示例来看,您似乎希望在React式管道的中间使用
Branch[]
对象,因为您使用它返回Flux<ResponseRepo>
。在这种情况下,请在Mono<Branch[]>
上使用map
或flatMap
。您可以按如下方式修改
getReposInfo
: