Spring webclient to make it generic for HTTP methods

852 Views Asked by At

I am working on webclient for various HTTP methods (GET,PATCH,POST,DELETE). These are created separately and invoke separately. I am looking to make it as a generic webclient component so minimum changes needs to do in the future. Below is the code for GET and POST. PATCH and Delete is also on similar lines. Please let me know how can I proceed to make generic webclient for various HTTP methods.

@Component
public class HuntsCreateNewCollectionAdapter {
    @Autowired
    AppProperties properties;

    @Autowired
    WebclientCollectionConfig webclientCollectionConfig;

    public Mono<ResponseEntity<HuntsCollectionDto>> createCollectionAPI(RequestContext context, String title) {
        LOGGER.debug("Create Collection API call");
        CollectionInputDto collectionInput = CollectionInputDto.builder().title(title).build();
        String json = AppJsonUtil.getJsonAsString(collectionInput);
        Mono<ResponseEntity<HuntsCollectionDto>> result = webclientCollectionConfig.collectionBuilder().post()
                .uri(properties.getCollectionUrl())
                .headers(header -> header.addAll(webclientCollectionConfig.getHeaders(context)))
                .body(BodyInserters.fromValue(json)).exchangeToMono(response -> {
                    return response.toEntity(HuntsCollectionDto.class);
                });
        return result;
    }
}

@Component
public class HuntsGetCollectionAdapter {
@Autowired
AppProperties properties;

@Autowired
WebclientCollectionConfig webclientCollectionConfig;

public Mono<ResponseEntity<HuntsCollectionDto>> getCollectionAPI(RequestContext context, String collectionId) {
    LOGGER.debug("Get Collection API call");
    return webclientCollectionConfig.collectionBuilder().get()
            .uri(properties.getCollectionUrl() + "/" + collectionId)
            .headers(header -> header.addAll(webclientCollectionConfig.getHeaders(context)))
            .exchangeToMono(response -> {
                return response.toEntity(HuntsCollectionDto.class);
            });
}

}

@Component
public class WebclientCollectionConfig {
    @Autowired
    AppProperties appProperties;

@Bean
public WebClient collectionBuilder() {
    return WebClient.builder().baseUrl(appProperties.getCollectionbaseUrl())
            .defaultHeader("Content-Type", "application/json").build();
}
}
0

There are 0 best solutions below