Reputation: 376
In my route I have one Post endpoint for which I expecting to accept the list of strings which I will then proccessing in handler.
My question is, how can I get these list of strings from ServerRequest body and iterate over them using Flux?
My Router
@Configuration
public class TestUrlRouter {
@Bean
public RouterFunction<ServerResponse> routes(TestUrlHandler handler) {
return RouterFunctions.route(
RequestPredicates.POST("/urls").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
handler::testUrls
);
}
}
My handler
@Component
public class TestUrlHandler {
@Autowired
private TestUrlService testUrlService;
public Mono<ServerResponse> testUrls(ServerRequest request) {
request.bodyToFlux(List.class) // how to iterate over strings?
}
}
Upvotes: 2
Views: 3881
Reputation: 376
I finally solved it by this code:
@Component
public class TestUrlHandler {
@Autowired
private TestUrlService testUrlService;
public Mono<ServerResponse> testUrls(ServerRequest request) {
ParallelFlux<TestUrlResult> results = request.bodyToMono(String[].class)
.flatMapMany(Flux::fromArray)
.flatMap(url -> testUrlService.testUrls(url))
.doOnComplete(() -> System.out.println("Testing of URLS is done."));
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(results, TestUrlResult.class);
}
}
Upvotes: 2
Reputation: 5283
There are lot of ways of achieving it.
Keeping it simple(modify as per your need).
protected static class WrapperList{
private List<String> urls;
// getter & setter
}
public Mono<ServerResponse> testUrls(ServerRequest request) {
return request.bodyToFlux(WrapperList.class).flatMap(wrapperList -> {
wrapperList.getUrls().stream().forEach(System.out::println);
return ServerResponse.ok().build();
}).take(1).next();
}
request payload:
{
"urls": ["url1","url2"]
}
Upvotes: 1