Skip to content

Commit

Permalink
Fixes with getting characters from database.
Browse files Browse the repository at this point in the history
  • Loading branch information
QbaSekowski committed Feb 19, 2024
1 parent 690b878 commit 2c59958
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
package mate.academy.rickandmorty.dto.external;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class CharactersInfoDto {
@JsonProperty("pages")
private int numberOfPages;
public record CharactersInfoDto(String next) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,14 @@ public class RickAndMortyClient {
private final ObjectMapper objectMapper;

public List<CharacterExternalResponseDto> getCharacters() {
int perPage = 20;
int currentPage = 1;
int numberOfPages;
List<CharacterExternalResponseDto> allCharacters = new ArrayList<>();
HttpClient httpClient = HttpClient.newHttpClient();
while (true) {
String urlWithPagination = BASE_URL + "?page=" + currentPage + "&per_page=" + perPage;
String url = BASE_URL;
while (url != null) {
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(urlWithPagination))
.uri(URI.create(url))
.build();

try {
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString());
Expand All @@ -40,14 +36,9 @@ public List<CharacterExternalResponseDto> getCharacters() {
response.body(), CharacterResponseDataDto.class);

allCharacters.addAll(characterResponseDataDto.getResults());
numberOfPages = characterResponseDataDto.getInfo().getNumberOfPages();

if (currentPage == numberOfPages) {
break;
}
currentPage++;
url = characterResponseDataDto.getInfo().next();
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
throw new RuntimeException("Can't load characters from given URL");
}
}
return allCharacters;
Expand Down

0 comments on commit 2c59958

Please sign in to comment.