|
|
@@ -1,15 +1,54 @@
|
|
|
package com.danielbohry.stocks.client;
|
|
|
|
|
|
import com.danielbohry.stocks.service.ExchangeService.ExchangeRateResponse;
|
|
|
-import org.springframework.cloud.openfeign.FeignClient;
|
|
|
-import org.springframework.web.bind.annotation.GetMapping;
|
|
|
-import org.springframework.web.bind.annotation.PathVariable;
|
|
|
+import lombok.RequiredArgsConstructor;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.springframework.http.HttpEntity;
|
|
|
+import org.springframework.http.HttpHeaders;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.web.client.HttpClientErrorException;
|
|
|
+import org.springframework.web.client.RestTemplate;
|
|
|
|
|
|
-@FeignClient(name = "exchangeClient", url = "${clients.exchange.url}")
|
|
|
-public interface ExchangeRateClient {
|
|
|
+import static org.springframework.http.HttpMethod.GET;
|
|
|
+import static org.springframework.http.HttpStatus.OK;
|
|
|
+import static org.springframework.http.MediaType.APPLICATION_JSON;
|
|
|
|
|
|
- @GetMapping("{token}/latest/{symbol}")
|
|
|
- ExchangeRateResponse getRate(@PathVariable("symbol") String symbol,
|
|
|
- @PathVariable("token") String apiKey);
|
|
|
+@Component
|
|
|
+@RequiredArgsConstructor
|
|
|
+public class ExchangeRateClient {
|
|
|
+
|
|
|
+ private final RestTemplate rest;
|
|
|
+
|
|
|
+ @Value("${clients.exchange.url}")
|
|
|
+ private String baseUrl;
|
|
|
+
|
|
|
+ public ExchangeRateResponse getRate(String symbol, String apiKey) {
|
|
|
+ String url = baseUrl + "/" + apiKey + "/latest/" + symbol;
|
|
|
+
|
|
|
+ HttpHeaders headers = new HttpHeaders();
|
|
|
+ headers.setContentType(APPLICATION_JSON);
|
|
|
+
|
|
|
+ HttpEntity<Void> entity = new HttpEntity<>(headers);
|
|
|
+
|
|
|
+ try {
|
|
|
+ ResponseEntity<ExchangeRateResponse> response = rest.exchange(
|
|
|
+ url,
|
|
|
+ GET,
|
|
|
+ entity,
|
|
|
+ ExchangeRateResponse.class
|
|
|
+ );
|
|
|
+
|
|
|
+ if (response.getStatusCode() == OK) {
|
|
|
+ return response.getBody();
|
|
|
+ } else {
|
|
|
+ throw new RuntimeException("Unexpected response status: " + response.getStatusCode());
|
|
|
+ }
|
|
|
+ } catch (HttpClientErrorException e) {
|
|
|
+ throw new RuntimeException("Error calling exchange API: " + e.getStatusCode() + " - " + e.getResponseBodyAsString());
|
|
|
+ } catch (Exception e) {
|
|
|
+ throw new RuntimeException("An error occurred calling exchange API: " + e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
}
|