Skip to content

Commit

Permalink
[BE-FEAT] 바이옴 세부 정보를 불러오는 API (#253)
Browse files Browse the repository at this point in the history
* refactor: txt파일 형식 변경에 따른 파싱 로직 수정

* feat: 바이옴 세부 정보 불러오는 API

* refactor: 바이옴, 트레이너 사진을 가져오도록 수정

* chore: 서브모듈 시점 변경

* refactor: findById의 반환 값 수정

* chore: 서브모듈 커밋 시점 변경

* chore: 서브모듈 커밋 시점 변경

* feat: 바이옴 세부정보 불러오는 기능

* chore: 서브모듈 커밋 시점 변경

* fix: 테스트 통과 못하는 오류 수정

* refactor: 아이디 형식 변경에 따른 수정

* chore: 서브모듈 커밋 시점 변경

* refactor: 불필요한 로그 삭제

* style: 개행 추가

* refactor: 포켓몬 이미지 url 전송 기능

* refactor: 초기화 과정에서 포켓몬 이미지 url 저장하도록 수정

* refactor: 필드 이름 변경

* refactor: 이미지 폴더 경로 수정

* refactor: 메서드명 수정

* fix: 트레이너나 포켓몬이 없을 시 오류처리하는 로직 수정

* fix: 트레이너나 포켓몬이 없을 시 오류처리하는 로직 수정

* refactor: 다음 바이옴 이름과 출현 확률 추가

* chore: 서브모듈 커밋 시점 변경

* refactor: 마지막 스테이지 다음 바이옴 빈값 반환하도록 수정
  • Loading branch information
unifolio0 authored Aug 20, 2024
1 parent 2fef4c5 commit 36cf9a6
Show file tree
Hide file tree
Showing 26 changed files with 533 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ public class S3Service {

private static final String POKEMON_IMAGE_FOLDER = "image/";
private static final String TYPE_IMAGE_FOLDER = "type/";
private static final String BIOME_IMAGE_FOLDER = "pokerogue/biome/";
private static final String TRAINER_IMAGE_FOLDER = "pokerogue/trainer/";
private static final String POKEROGUE_TYPE_IMAGE_FOLDER = "pokerogue/type/";
private static final String POKEROGUE_MOVE_CATEGORY_IMAGE_FOLDER = "pokerogue/move-category/";
private static final String POKEROGUE_POKEMON_IMAGE_FOLDER = "pokerogue/pokemon/front/";
private static final String SVG_EXTENSION = ".svg";
private static final String PNG_EXTENSION = ".png";

Expand All @@ -33,6 +36,24 @@ public String getTypeImageFromS3(String typeName) {
return s3ImageClient.getFileUrl(key);
}

public String getBiomeImageFromS3(String biomeId) {
String key = makeBiomeFileName(biomeId);
return s3ImageClient.getFileUrl(key);
}

private String makeBiomeFileName(String biomeId) {
return BIOME_IMAGE_FOLDER + biomeId + PNG_EXTENSION;
}

public String getTrainerImageFromS3(String trainerId) {
String key = makeTrainerFileName(trainerId);
return s3ImageClient.getFileUrl(key);
}

private String makeTrainerFileName(String trainerId) {
return TRAINER_IMAGE_FOLDER + trainerId + PNG_EXTENSION;
}

private String makeRandomFileName() {
return POKEMON_IMAGE_FOLDER + UUID.randomUUID();
}
Expand All @@ -45,4 +66,13 @@ public String getPokerogueTypeImageFromS3(String typeName) {
String key = POKEROGUE_TYPE_IMAGE_FOLDER + typeName + "-1" + PNG_EXTENSION;
return s3ImageClient.getFileUrl(key);
}

public String getPokemonImageFromS3(String pokemonId) {
String key = makePokemonFileName(pokemonId);
return s3ImageClient.getFileUrl(key);
}

private String makePokemonFileName(String pokemonId) {
return POKEROGUE_POKEMON_IMAGE_FOLDER + pokemonId + PNG_EXTENSION;
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
package com.pokerogue.helper.biome.config;

import com.pokerogue.external.s3.service.S3Service;
import com.pokerogue.helper.biome.data.Biome;
import com.pokerogue.helper.biome.data.BiomeLink;
import com.pokerogue.helper.biome.data.BiomePokemon;
import com.pokerogue.helper.biome.data.BiomePokemonInfo;
import com.pokerogue.helper.biome.data.BiomePokemonType;
import com.pokerogue.helper.biome.data.BiomeTypeAndTrainer;
import com.pokerogue.helper.biome.data.NextBiome;
import com.pokerogue.helper.biome.data.PokemonByBiome;
import com.pokerogue.helper.biome.data.Tier;
import com.pokerogue.helper.biome.data.Trainer;
import com.pokerogue.helper.biome.data.TrainerPokemon;
import com.pokerogue.helper.biome.data.TrainerType;
import com.pokerogue.helper.biome.repository.BiomePokemonInfoRepository;
import com.pokerogue.helper.biome.repository.BiomePokemonTypeImageRepository;
import com.pokerogue.helper.biome.repository.BiomeRepository;
import com.pokerogue.helper.global.exception.ErrorMessage;
import com.pokerogue.helper.global.exception.GlobalCustomException;
Expand All @@ -16,6 +23,7 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand All @@ -30,7 +38,10 @@
@RequiredArgsConstructor
public class BiomeDatabaseInitializer implements ApplicationRunner {

private final S3Service s3Service;
private final BiomePokemonTypeImageRepository biomePokemonTypeImageRepository;
private final BiomeRepository biomeRepository;
private final BiomePokemonInfoRepository biomePokemonInfoRepository;

@Override
public void run(ApplicationArguments args) {
Expand All @@ -39,6 +50,7 @@ public void run(ApplicationArguments args) {
List<BiomeTypeAndTrainer> biomeTypesAndTrainers = new ArrayList<>();
List<TrainerType> trainerTypes = new ArrayList<>();
List<TrainerPokemon> trainerPokemons = new ArrayList<>();
List<PokemonByBiome> pokemonByBiomes = new ArrayList<>();

try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("biome-pokemons.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
Expand Down Expand Up @@ -92,7 +104,7 @@ public void run(ApplicationArguments args) {
log.error("error message : {}", e.getStackTrace()[0]);
}

try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("trainer-types.txt");
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("trainer-pokemons.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
while (true) {
String trainerPokemon = bufferedReader.readLine();
Expand All @@ -105,30 +117,82 @@ public void run(ApplicationArguments args) {
log.error("error message : {}", e.getStackTrace()[0]);
}

List<Trainer> trainers = trainerTypes.stream()
.map(trainerType -> new Trainer(trainerType.getTrainerName(), trainerType.getTrainerTypes(),
getTrainerPokemons(trainerPokemons, trainerType.getTrainerName())))
.toList();
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("pokemon-by-biome.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
while (true) {
String pokemonByBiome = bufferedReader.readLine();
if (pokemonByBiome == null) {
break;
}
pokemonByBiomes.add(new PokemonByBiome(pokemonByBiome));
}
} catch (IOException e) {
log.error("error message : {}", e.getStackTrace()[0]);
}

List<Trainer> trainers = trainerPokemons.stream()
.filter(trainerPokemon -> existsByTrainerName(trainerTypes, trainerPokemon.getTrainerName()))
.map(trainerPokemon -> new Trainer(
trainerPokemon.getId(),
trainerPokemon.getTrainerName(),
s3Service.getTrainerImageFromS3(trainerPokemon.getId()),
getTrainerTypes(trainerTypes, trainerPokemon.getTrainerName()),
trainerPokemon.getTrainerPokemons())
).toList();

biomeTypesAndTrainers.stream()
.map(biomeTypeAndTrainer -> new Biome(
biomeTypeAndTrainer.getId(),
biomeTypeAndTrainer.getBiomeName(),
biomeTypeAndTrainer.getBiomeName(),
s3Service.getBiomeImageFromS3(biomeTypeAndTrainer.getId()),
getBiomePokemons(biomePokemons, biomeTypeAndTrainer.getBiomeName()),
biomeTypeAndTrainer.getBiomeTypes(),
getBiomeTrainers(trainers, biomeTypeAndTrainer.getTrainerNames()),
getNextBiomes(biomeLinks, biomeTypeAndTrainer.getBiomeName()))
getNextBiomes(biomeLinks, biomeTypeAndTrainer.getId()))
)
.forEach(biomeRepository::save);

pokemonByBiomes.stream()
.map(pokemonByBiome -> new BiomePokemonInfo(
pokemonByBiome.getId(),
pokemonByBiome.getName(),
s3Service.getPokemonImageFromS3(pokemonByBiome.getId()),
BiomePokemonType.getBiomePokemonTypeByName(pokemonByBiome.getType1()),
BiomePokemonType.getBiomePokemonTypeByName(pokemonByBiome.getType2())
))
.forEach(biomePokemonInfoRepository::save);

Arrays.stream(BiomePokemonType.values())
.forEach(biomePokemonType -> biomePokemonTypeImageRepository.save(
biomePokemonType.name(),
s3Service.getPokerogueTypeImageFromS3(biomePokemonType.name().toLowerCase()))
);
}

private boolean existsByTrainerName(List<TrainerType> trainerTypes, String trainerName) {
return trainerTypes.stream()
.anyMatch(trainerType -> trainerType.getTrainerName().equals(trainerName));
}

private List<String> getTrainerTypes(List<TrainerType> trainerTypes, String trainerName) {
return trainerTypes.stream()
.filter(trainerType -> trainerType.getTrainerName().equals(trainerName))
.map(TrainerType::getTrainerTypes)
.findFirst()
.orElseThrow(() -> new GlobalCustomException(ErrorMessage.TRAINER_NOT_FOUND));
}

private Map<Tier, List<String>> getBiomePokemons(List<BiomePokemon> biomePokemons, String biomeName) {
List<BiomePokemon> allBiomePokemons = biomePokemons.stream()
.filter(biomePokemon -> biomePokemon.getBiomeName().equals(biomeName))
.filter(biomePokemon -> !biomePokemon.getPokemons().contains("없음"))
.toList();

Map<Tier, List<String>> ret = new HashMap<>();
for (BiomePokemon biomePokemon : allBiomePokemons) {
if (biomePokemon.getPokemons().contains("없음")) {
continue;
}
if (ret.containsKey(biomePokemon.getPokemonTier())) {
List<String> pokemons = ret.get(biomePokemon.getPokemonTier());
pokemons.addAll(biomePokemon.getPokemons());
Expand All @@ -146,19 +210,11 @@ private List<Trainer> getBiomeTrainers(List<Trainer> trainers, List<String> trai
.toList();
}

private List<String> getNextBiomes(List<BiomeLink> biomeLinks, String biomeName) {
private List<NextBiome> getNextBiomes(List<BiomeLink> biomeLinks, String biomeId) {
return biomeLinks.stream()
.filter(biomeLink -> biomeLink.getCurrentBiome().equals(biomeName))
.filter(biomeLink -> biomeLink.getId().equals(biomeId))
.map(BiomeLink::getNextBiomes)
.findFirst()
.orElseThrow(() -> new GlobalCustomException(ErrorMessage.BIOME_NOT_FOUND));
}

private List<String> getTrainerPokemons(List<TrainerPokemon> trainerPokemons, String trainerName) {
return trainerPokemons.stream()
.filter(trainerPokemon -> trainerPokemon.getTrainerName().equals(trainerName))
.map(TrainerPokemon::getTrainerPokemons)
.findFirst()
.orElseThrow(() -> new GlobalCustomException(ErrorMessage.TRAINER_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.pokerogue.helper.biome.controller;

import com.pokerogue.helper.biome.dto.BiomeResponse;
import com.pokerogue.helper.biome.dto.BiomeDetailResponse;
import com.pokerogue.helper.biome.service.BiomeService;
import com.pokerogue.helper.util.dto.ApiResponse;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
Expand All @@ -20,4 +22,11 @@ public class BiomeController {
public ApiResponse<List<BiomeResponse>> biomeList() {
return new ApiResponse<>("바이옴 리스트 불러오기에 성공했습니다.", biomeService.findBiomes());
}

@GetMapping("/api/v1/biome/{id}")
public ApiResponse<BiomeDetailResponse> biomeDetails(@PathVariable("id") String id) {
log.info("---- URI : {}, Param : {}", "/api/v1/biome/{id}", id);

return new ApiResponse<>("바이옴 정보 불러오기에 성공했습니다.", biomeService.findBiome(id));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,25 @@
import java.util.Map;
import java.util.Set;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class Biome {

private final String id;
private final String name;
private final String image;
private final Map<Tier, List<String>> pokemons;
private final List<String> mainTypes;
private final List<Trainer> trainers;
private final List<String> nextBiomeNames;

public Biome(
String id,
String name,
Map<Tier, List<String>> pokemons,
List<String> mainTypes,
List<Trainer> trainers,
List<String> nextBiomeNames
) {
this.id = id;
this.name = name;
this.pokemons = pokemons;
this.mainTypes = mainTypes;
this.trainers = trainers;
this.nextBiomeNames = nextBiomeNames;
}
private final List<NextBiome> nextBiome;

public List<String> getTrainerTypes() {
Set<String> trainerTypes = new HashSet<>();
trainers.forEach(trainer -> trainerTypes.addAll(trainer.getTrainerTypes()));
trainers.stream()
.filter(trainer -> !trainer.getName().equals("없음"))
.forEach(trainer -> trainerTypes.addAll(trainer.getTrainerTypes()));

return trainerTypes.stream()
.toList();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
package com.pokerogue.helper.biome.data;

import java.util.Arrays;
import java.util.List;
import lombok.Getter;

@Getter
public class BiomeLink {

private final String id;
private final String currentBiome;
private final List<String> nextBiomes;
private final List<NextBiome> nextBiomes;

public BiomeLink(String biomeLink) {
String[] biomeLinkInforms = biomeLink.split(" / ");
this.currentBiome = biomeLinkInforms[0];
this.nextBiomes = List.of(biomeLinkInforms[1].split(","));
this.id = biomeLinkInforms[0];
this.currentBiome = biomeLinkInforms[1];
this.nextBiomes = Arrays.stream(biomeLinkInforms[2].split(","))
.map(s -> new NextBiome(s.split("~")[0], s.split("~")[1]))
.toList();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.pokerogue.helper.biome.data;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class BiomePokemonInfo {

private final String id;
private final String name;
private final String image;
private final BiomePokemonType type1;
private final BiomePokemonType type2;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.pokerogue.helper.biome.data;

import com.pokerogue.helper.global.exception.ErrorMessage;
import com.pokerogue.helper.global.exception.GlobalCustomException;
import java.util.Arrays;
import lombok.Getter;

@Getter
public enum BiomePokemonType {

GRASS("풀"),
POISON("독"),
FIRE("불꽃"),
WATER("물"),
ELECTRIC("전기"),
NORMAL("노말"),
FAIRY("페어리"),
BUG("벌레"),
DARK("악"),
DRAGON("드래곤"),
FIGHTING("격투"),
FLYING("비행"),
GHOST("고스트"),
GROUND("땅"),
ICE("얼음"),
ROCK("바위"),
PSYCHIC("에스퍼"),
STEEL("강철"),
STELLAR("스텔라"),
UNKNOWN("없음");

private final String name;

BiomePokemonType(String name) {
this.name = name;
}

public static BiomePokemonType getBiomePokemonTypeByName(String name) {
return Arrays.stream(values())
.filter(biomePokemonType -> biomePokemonType.name.equals(name))
.findFirst()
.orElseThrow(() -> new GlobalCustomException(ErrorMessage.POKEMON_TYPE_NOT_FOUND));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@
@Getter
public class BiomeTypeAndTrainer {

private final String id;
private final String biomeName;
private final List<String> biomeTypes;
private final List<String> trainerNames;

public BiomeTypeAndTrainer(String biomeTypeAndTrainer) {
String[] biomeTypeAndTrainerInforms = biomeTypeAndTrainer.split(" / ");
this.biomeName = biomeTypeAndTrainerInforms[0];
this.biomeTypes = List.of(biomeTypeAndTrainerInforms[1].split(","));
this.trainerNames = List.of(biomeTypeAndTrainerInforms[2].split(","));
this.id = biomeTypeAndTrainerInforms[0];
this.biomeName = biomeTypeAndTrainerInforms[1];
this.biomeTypes = List.of(biomeTypeAndTrainerInforms[2].split(","));
this.trainerNames = List.of(biomeTypeAndTrainerInforms[3].split(","));
}
}
Loading

0 comments on commit 36cf9a6

Please sign in to comment.