Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Rick & Morty API #6

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 53 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,34 @@
<maven.checkstyle.plugin.configLocation>
https://raw.githubusercontent.com/mate-academy/style-guides/master/java/checkstyle.xml
</maven.checkstyle.plugin.configLocation>
<mysql.version>8.0.33</mysql.version>
<openapi.version>2.0.3</openapi.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<lombok.mapstruct.binding.version>0.2.0</lombok.mapstruct.binding.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${openapi.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand All @@ -36,7 +57,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
Expand Down Expand Up @@ -66,6 +91,32 @@
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
<sourceDirectories>src</sourceDirectories>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>${lombok.mapstruct.binding.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package mate.academy.rickandmorty.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.external.CharacterResponseDataDto;
import mate.academy.rickandmorty.dto.external.ExternalCharacterDto;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

@RequiredArgsConstructor
@Configuration
public class DataFetchConfig {
private final CharacterService service;
private final ObjectMapper objectMapper;
@Value("${rickandmorty.api.url}")
private String characterUrl;

@EventListener(ApplicationReadyEvent.class)
public void fetchData() {
List<ExternalCharacterDto> characters = new ArrayList<>();
CharacterResponseDataDto response = loadData(characterUrl);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
CharacterResponseDataDto response = loadData(characterUrl);
CharacterResponseDataDto characterResponse = loadData(characterUrl);

do {
characters.addAll(response.results());
response = loadData(response.info().next());
} while (response.info().next() != null);
service.saveAll(characters);
}

private CharacterResponseDataDto loadData(String url) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OPTIONAL: As an alternative way to make http requests it is possible to use feignClient, which from my point of view is a more suitable and agile way of making web clients and request. But actually for current task your solution in ok as well

HttpClient httpClient = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(url))
.build();

try {
HttpResponse<byte[]> response = httpClient.send(
request,
HttpResponse.BodyHandlers.ofByteArray()
);
return objectMapper.readValue(
response.body(), new TypeReference<>() {
}
);
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is better to throw custom exception instead of generic one

}
}
}
13 changes: 13 additions & 0 deletions src/main/java/mate/academy/rickandmorty/config/MapperConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package mate.academy.rickandmorty.config;

import org.mapstruct.InjectionStrategy;
import org.mapstruct.NullValueCheckStrategy;

@org.mapstruct.MapperConfig(
componentModel = "spring",
injectionStrategy = InjectionStrategy.CONSTRUCTOR,
nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS,
implementationPackage = "<PACKAGE_NAME>.impl"
)
public class MapperConfig {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package mate.academy.rickandmorty.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "Character API", description = "Look at and search for characters")
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/characters")
public class CharacterController {
private final CharacterService characterService;

@Operation(
summary = "Get random character",
description = "The request randomly generates a wiki about one"
+ " character in the universe the animated series Rick & Morty"
)
@GetMapping("/random")
public CharacterResponseDto getRandom() {
return characterService.getRandom();
}

@Operation(
summary = "Search character",
description = "Search for characters based on the name"
)
@GetMapping("/search")
public List<CharacterResponseDto> search(@RequestParam String name) {
return characterService.search(name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package mate.academy.rickandmorty.dto;

public record CharacterResponseDto(
Long id,
Long externalId,
String name,
String status,
String gender
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package mate.academy.rickandmorty.dto.external;

import java.util.List;

public record CharacterResponseDataDto(
ExternalCharacterInfoDto info,
List<ExternalCharacterDto> results
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package mate.academy.rickandmorty.dto.external;

public record ExternalCharacterDto(Long id, String name, String status, String gender) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package mate.academy.rickandmorty.dto.external;

public record ExternalCharacterInfoDto(Long count, Long pages, String next, String prev) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package mate.academy.rickandmorty.mapper;

import mate.academy.rickandmorty.config.MapperConfig;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import mate.academy.rickandmorty.dto.external.ExternalCharacterDto;
import mate.academy.rickandmorty.model.Character;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper(config = MapperConfig.class)
public interface CharacterMapper {
CharacterResponseDto toDto(Character character);

@Mapping(target = "externalId", source = "id")
@Mapping(target = "id", ignore = true)
Character toModel(ExternalCharacterDto characterDto);
}
22 changes: 22 additions & 0 deletions src/main/java/mate/academy/rickandmorty/model/Character.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package mate.academy.rickandmorty.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table(name = "characters")
public class Character {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long externalId;
private String name;
private String status;
private String gender;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mate.academy.rickandmorty.repository;

import java.util.List;
import mate.academy.rickandmorty.model.Character;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CharacterRepository extends JpaRepository<Character, Long> {
List<Character> findCharacterByNameContaining(String name);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package mate.academy.rickandmorty.service;

import java.util.List;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import mate.academy.rickandmorty.dto.external.ExternalCharacterDto;
import mate.academy.rickandmorty.model.Character;

public interface CharacterService {
CharacterResponseDto getRandom();

List<CharacterResponseDto> search(String name);

List<Character> saveAll(List<ExternalCharacterDto> externalCharacterDtos);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package mate.academy.rickandmorty.service.impl;

import java.util.List;
import java.util.Random;
import lombok.RequiredArgsConstructor;
import mate.academy.rickandmorty.dto.CharacterResponseDto;
import mate.academy.rickandmorty.dto.external.ExternalCharacterDto;
import mate.academy.rickandmorty.mapper.CharacterMapper;
import mate.academy.rickandmorty.model.Character;
import mate.academy.rickandmorty.repository.CharacterRepository;
import mate.academy.rickandmorty.service.CharacterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service
public class CharacterServiceImpl implements CharacterService {
private static final long minId = 1L;
private final CharacterRepository characterRepository;
private final CharacterMapper characterMapper;

@Override
public CharacterResponseDto getRandom() {
long numberOfCharacters = characterRepository.count();
Random random = new Random();
long randomId = random.nextLong(numberOfCharacters + minId);
return characterRepository.findById(randomId)
.map(characterMapper::toDto)
.orElseThrow();
}

@Override
public List<CharacterResponseDto> search(String name) {
return characterRepository.findCharacterByNameContaining(name)
.stream()
.map(characterMapper::toDto)
.toList();
}

@Transactional
@Override
public List<Character> saveAll(List<ExternalCharacterDto> externalCharacterDtos) {
List<Character> characters = externalCharacterDtos.stream()
.map(characterMapper::toModel)
.toList();
return characterRepository.saveAll(characters);
}
}
10 changes: 10 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
spring.datasource.url=jdbc:mysql://localhost:3306/rick_and_morty
spring.datasource.username=test
spring.datasource.password=StrongSecret1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.open-in-view=false

server.servlet.context-path=/api

rickandmorty.api.url=https://rickandmortyapi.com/api/character
8 changes: 3 additions & 5 deletions src/test/java/mate/academy/rickandmorty/ApplicationTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@

@SpringBootTest
class ApplicationTests {

@Test
void contextLoads() {
}

@Test
void contextLoads() {
}
}
7 changes: 7 additions & 0 deletions src/test/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,10 @@ spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.open-in-view=false

server.servlet.context-path=/api

rickandmorty.api.url=https://rickandmortyapi.com/api/character