Skip to content

Commit

Permalink
Merge pull request #125 from UMC-TripPiece/refactor/122
Browse files Browse the repository at this point in the history
[refactor] S3 파일 업로드 용량 / 이모지 및 맵 Request 수정
  • Loading branch information
StoneCAU authored Jan 23, 2025
2 parents d747d71 + 4927ea7 commit 9eef79c
Show file tree
Hide file tree
Showing 9 changed files with 78 additions and 59 deletions.
4 changes: 2 additions & 2 deletions src/main/java/umc/TripPiece/converter/MapConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
public class MapConverter {

// MapRequestDto -> Map 변환
public static Map toMap(MapRequestDto requestDto, City city) {
public static Map toMap(MapRequestDto requestDto, City city, Long userId) {
return new Map(
null,
requestDto.getUserId(),
userId,
requestDto.getCountryCode(),
requestDto.getColor(), // String 값 그대로 설정
Collections.emptyList(),
Expand Down
32 changes: 23 additions & 9 deletions src/main/java/umc/TripPiece/service/MapService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import umc.TripPiece.domain.enums.Color;
import umc.TripPiece.domain.jwt.JWTUtil;
import umc.TripPiece.repository.*;
import umc.TripPiece.security.SecurityUtils;
import umc.TripPiece.web.dto.request.MapRequestDto;
import umc.TripPiece.web.dto.response.MapResponseDto;
import umc.TripPiece.web.dto.response.MapStatsResponseDto;
Expand All @@ -32,24 +33,28 @@ public class MapService {
private final UserRepository userRepository;
private final CountryRepository countryRepository;

public List<MapResponseDto> getMapsByUserId(Long userId) {
public List<MapResponseDto> getUserMaps() {
Long userId = SecurityUtils.getCurrentUserId();

return mapRepository.findByUserId(userId).stream()
.map(MapConverter::toMapResponseDto)
.collect(Collectors.toList());
}

@Transactional
public MapResponseDto createMapWithCity(MapRequestDto requestDto) {
Long userId = SecurityUtils.getCurrentUserId();

mapRepository.findByUserIdAndCountryCodeAndCityId(
requestDto.getUserId(), requestDto.getCountryCode(), requestDto.getCityId())
userId, requestDto.getCountryCode(), requestDto.getCityId())
.ifPresent(existingMap -> {
throw new IllegalArgumentException("이미 색칠된 도시입니다.");
});

City city = cityRepository.findById(requestDto.getCityId())
.orElseThrow(() -> new IllegalArgumentException("City not found with id: " + requestDto.getCityId()));

Map map = MapConverter.toMap(requestDto, city);
Map map = MapConverter.toMap(requestDto, city, userId);
Map savedMap = mapRepository.save(map);
return MapConverter.toMapResponseDto(savedMap);
}
Expand All @@ -65,7 +70,9 @@ public MapResponseDto updateMapColor(Long mapId, String newColor) {
}

@Transactional
public MapResponseDto updateMapColorWithInfo(Long userId, String countryCode, Long cityId, String newColor) {
public MapResponseDto updateMapColorWithInfo(String countryCode, Long cityId, String newColor) {
Long userId = SecurityUtils.getCurrentUserId();

Map map = mapRepository.findByUserIdAndCountryCodeAndCityId(userId, countryCode, cityId)
.orElseThrow(() -> new IllegalArgumentException("Map not found with provided info."));

Expand All @@ -84,7 +91,9 @@ public void deleteMapColor(Long mapId) {
}

@Transactional
public void deleteMapWithInfo(Long userId, String countryCode, Long cityId) {
public void deleteMapWithInfo(String countryCode, Long cityId) {
Long userId = SecurityUtils.getCurrentUserId();

List<Map> maps = mapRepository.findAllByUserIdAndCountryCodeAndCityId(userId, countryCode, cityId);
if (maps.isEmpty()) {
throw new IllegalArgumentException("해당 정보로 등록된 맵이 없습니다.");
Expand All @@ -103,7 +112,9 @@ public MapResponseDto updateMultipleMapColors(Long mapId, List<String> colorStri
return MapConverter.toMapResponseDto(updatedMap);
}

public MapStatsResponseDto getMapStatsByUserId(Long userId) {
public MapStatsResponseDto getUserMapStats() {
Long userId = SecurityUtils.getCurrentUserId();

long countryCount = mapRepository.countDistinctCountryCodeByUserId(userId);
long cityCount = mapRepository.countDistinctCityByUserId(userId);

Expand Down Expand Up @@ -131,7 +142,9 @@ public long getVisitedCountryCount(Long userId) {
return mapRepository.countDistinctCountryCodeByUserId(userId);
}

public MapStatsResponseDto getVisitedCountriesWithProfile(Long userId) {
public MapStatsResponseDto getVisitedCountriesWithProfile() {
Long userId = SecurityUtils.getCurrentUserId();

List<String> visitedCountries = getVisitedCountries(userId);
long visitedCountryCount = getVisitedCountryCount(userId);

Expand Down Expand Up @@ -172,8 +185,9 @@ public List<MapResponseDto.searchDto> searchCitiesCountry(String keyword) {
return results;
}

public List<MapResponseDto.getMarkerResponse> getMarkers(String token) {
Long userId = jwtUtil.getUserIdFromToken(token);
public List<MapResponseDto.getMarkerResponse> getUserMarkers() {
Long userId = SecurityUtils.getCurrentUserId();

List<Map> maps = mapRepository.findByUserId(userId);

return maps.stream()
Expand Down
14 changes: 11 additions & 3 deletions src/main/java/umc/TripPiece/service/TravelService.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
import umc.TripPiece.repository.VideoRepository;
import umc.TripPiece.security.SecurityUtils;
import umc.TripPiece.web.dto.request.TravelRequestDto;
import umc.TripPiece.web.dto.request.TravelRequestDto.EmojiDto;
import umc.TripPiece.web.dto.request.TravelRequestDto.MemoDto;
import umc.TripPiece.web.dto.response.TravelResponseDto;

@Service
Expand Down Expand Up @@ -94,14 +96,16 @@ public TripPiece createMemo(Long travelId, TravelRequestDto.MemoDto request) {
}

@Transactional
public TripPiece createEmoji(Long travelId, List<String> emojis, TravelRequestDto.MemoDto request) {
public TripPiece createEmoji(Long travelId, EmojiDto request) {
Long userId = SecurityUtils.getCurrentUserId();
User user = userRepository.findById(userId)
.orElseThrow(() -> new NotFoundHandler(ErrorStatus.NOT_FOUND_USER));

Travel travel = travelRepository.findById(travelId)
.orElseThrow(() -> new NotFoundHandler(ErrorStatus.NOT_FOUND_TRAVEL));

List<String> emojis = request.getEmojis();

// 메모 검증
if (request.getDescription().length() > 100) {
throw new BadRequestHandler(ErrorStatus.TEXT_LENGTH_100_ERROR);
Expand All @@ -127,7 +131,11 @@ public TripPiece createEmoji(Long travelId, List<String> emojis, TravelRequestDt
}
}

TripPiece newTripPiece = TravelConverter.toTripPieceMemo(request, user);

TripPiece newTripPiece = TripPiece.builder()
.description(request.getDescription())
.user(user)
.build();

// 이모지 생성
for (String emoji : emojis) {
Expand Down Expand Up @@ -561,4 +569,4 @@ private List<Picture> getPictures(Travel travel) {

return pictures;
}
}
}
12 changes: 7 additions & 5 deletions src/main/java/umc/TripPiece/service/TripPieceService.java
Original file line number Diff line number Diff line change
Expand Up @@ -261,14 +261,16 @@ public void delete(Long id) {
// 사진 삭제
List<Picture> pictures = pictureRepository.findByTripPieceId(id);
pictureRepository.deleteAll(pictures);
pictures.forEach(picture -> s3Manager.deleteFile(picture.getPictureUrl()));

// 영상 삭제
List<Video> videos = videoRepository.findByTripPieceId(id);
videoRepository.deleteAll(videos);
videos.forEach(video -> s3Manager.deleteFile(video.getVideoUrl()));

// 여행 조각 삭제
TripPiece tripPiece = tripPieceRepository.findById(id)
.orElseThrow(() -> new NotFoundHandler(ErrorStatus.NOT_FOUND_TRIPPIECE));
.orElseThrow(() -> new NotFoundHandler(ErrorStatus.NOT_FOUND_TRIPPIECE));

tripPieceRepository.delete(tripPiece);
}
Expand All @@ -294,7 +296,7 @@ public Long pictureUpdate(Long id, TripPieceRequestDto.update request, List<Mult

// 원래 여행조각의 타입이 PICTURE 또는 SELFIE 인지 검사
if (tripPiece.getCategory() != Category.PICTURE
&& tripPiece.getCategory() != Category.SELFIE)
&& tripPiece.getCategory() != Category.SELFIE)
throw new BadRequestHandler(ErrorStatus.INVALID_TRIPPIECE_CATEGORY);

// 기존에 저장되어있던 사진들은 모두 삭제
Expand All @@ -309,7 +311,7 @@ public Long pictureUpdate(Long id, TripPieceRequestDto.update request, List<Mult
for(int i = 0; i < pictureNum; i++) {
String uuid = UUID.randomUUID().toString();
Uuid savedUuid = uuidRepository.save(Uuid.builder()
.uuid(uuid).build());
.uuid(uuid).build());
uuids.add(savedUuid);
}

Expand All @@ -336,7 +338,7 @@ public Long videoUpdate(Long id, TripPieceRequestDto.update request, MultipartFi

// 원래 여행조각의 타입이 VIDEO 또는 WHERE 인지 검사
if (tripPiece.getCategory() != Category.VIDEO
&& tripPiece.getCategory() != Category.WHERE)
&& tripPiece.getCategory() != Category.WHERE)
throw new BadRequestHandler(ErrorStatus.INVALID_TRIPPIECE_CATEGORY);

// 기존에 저장되어있던 비디오들은 모두 삭제
Expand All @@ -348,7 +350,7 @@ public Long videoUpdate(Long id, TripPieceRequestDto.update request, MultipartFi

String uuid = UUID.randomUUID().toString();
Uuid savedUuid = uuidRepository.save(Uuid.builder()
.uuid(uuid).build());
.uuid(uuid).build());

String videoUrl = s3Manager.uploadFile(s3Manager.generateTripPieceKeyName(savedUuid), file, Category.VIDEO);

Expand Down
39 changes: 16 additions & 23 deletions src/main/java/umc/TripPiece/web/controller/MapController.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,11 @@
public class MapController {

private final MapService mapService;
private final JWTUtil jwtUtil; // JWTUtil 객체 주입

@GetMapping("/{userId}")
@GetMapping
@Operation(summary = "유저별 맵 불러오기 API", description = "유저별 맵 리스트 반환")
public ApiResponse<List<MapResponseDto>> getMapsByUserId(@PathVariable(name = "userId") @ExistEntity(entityType = umc.TripPiece.domain.User.class) Long userId) {
List<MapResponseDto> maps = mapService.getMapsByUserId(userId);
public ApiResponse<List<MapResponseDto>> getMaps() {
List<MapResponseDto> maps = mapService.getUserMaps();
return ApiResponse.onSuccess(maps);
}

Expand All @@ -49,18 +48,17 @@ public ApiResponse<MapResponseDto> createMap(@RequestBody @Valid MapRequestDto r
return ApiResponse.onSuccess(mapResponseDto);
}

@GetMapping("/stats/{userId}")
@GetMapping("/stats")
@Operation(summary = "유저별 맵 통계 API", description = "유저별 방문한 나라와 도시 수 반환")
public ApiResponse<MapStatsResponseDto> getMapStatsByUserId(@PathVariable(name = "userId") Long userId) {
MapStatsResponseDto stats = mapService.getMapStatsByUserId(userId);
public ApiResponse<MapStatsResponseDto> getMapStats() {
MapStatsResponseDto stats = mapService.getUserMapStats();
return ApiResponse.onSuccess(stats);
}

@GetMapping("/markers")
@Operation(summary = "구글 지도 위 마커 반환 API", description = "나의 기록탭의 마커 반환")
public ApiResponse<List<MapResponseDto.getMarkerResponse>> getMarkers(@RequestHeader("Authorization") String token) {
String tokenWithoutBearer = token.substring(7);
List<MapResponseDto.getMarkerResponse> markers = mapService.getMarkers(tokenWithoutBearer);
public ApiResponse<List<MapResponseDto.getMarkerResponse>> getMarkers() {
List<MapResponseDto.getMarkerResponse> markers = mapService.getUserMarkers();
return ApiResponse.onSuccess(markers);
}

Expand All @@ -86,28 +84,23 @@ public ApiResponse<MapResponseDto> updateMultipleMapColors(@PathVariable(name =
}

@PutMapping("/color")
@Operation(summary = "맵 색상 수정 (기존 정보 기반)", description = "맵의 색상을 수정 (userId, countryCode, cityId 기반)")
public ApiResponse<MapResponseDto> updateMapColorWithInfo(@RequestHeader("Authorization") String token,
@RequestBody @Valid MapRequestDto requestDto) {
Long userId = jwtUtil.getUserIdFromToken(token.substring(7));
MapResponseDto updatedMap = mapService.updateMapColorWithInfo(userId, requestDto.getCountryCode(), requestDto.getCityId(), requestDto.getColor());
@Operation(summary = "맵 색상 수정 (기존 정보 기반)", description = "맵의 색상을 수정 ( countryCode, cityId 기반)")
public ApiResponse<MapResponseDto> updateMapColorWithInfo(@RequestBody @Valid MapRequestDto requestDto) {
MapResponseDto updatedMap = mapService.updateMapColorWithInfo(requestDto.getCountryCode(), requestDto.getCityId(), requestDto.getColor());
return ApiResponse.onSuccess(updatedMap);
}

@DeleteMapping("/color")
@Operation(summary = "맵 삭제 (기존 정보 기반)", description = "맵을 삭제 (userId, countryCode, cityId 기반)")
public ApiResponse<Void> deleteMapWithInfo(@RequestHeader("Authorization") String token,
@RequestBody @Valid MapRequestDto requestDto) {
Long userId = jwtUtil.getUserIdFromToken(token.substring(7));
mapService.deleteMapWithInfo(userId, requestDto.getCountryCode(), requestDto.getCityId());
@Operation(summary = "맵 삭제 (기존 정보 기반)", description = "맵을 삭제 (countryCode, cityId 기반)")
public ApiResponse<Void> deleteMapWithInfo(@RequestBody @Valid MapRequestDto requestDto) {
mapService.deleteMapWithInfo(requestDto.getCountryCode(), requestDto.getCityId());
return ApiResponse.onSuccess(null);
}

@GetMapping("/visited-countries")
@Operation(summary = "방문한 나라 누적 API", description = "사용자가 방문한 나라의 리스트와 카운트를 반환")
public ApiResponse<MapStatsResponseDto> getVisitedCountries(@RequestHeader("Authorization") String token) {
Long userId = jwtUtil.getUserIdFromToken(token.substring(7));
MapStatsResponseDto response = mapService.getVisitedCountriesWithProfile(userId);
public ApiResponse<MapStatsResponseDto> getVisitedCountries() {
MapStatsResponseDto response = mapService.getVisitedCountriesWithProfile();
return ApiResponse.onSuccess(response);
}

Expand Down
15 changes: 3 additions & 12 deletions src/main/java/umc/TripPiece/web/controller/TravelController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,21 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import umc.TripPiece.apiPayload.code.status.ErrorStatus;
import umc.TripPiece.apiPayload.exception.GeneralException;
import umc.TripPiece.apiPayload.exception.handler.BadRequestHandler;
import umc.TripPiece.converter.TravelConverter;
import umc.TripPiece.domain.Travel;
import umc.TripPiece.domain.TripPiece;
import umc.TripPiece.domain.enums.TravelStatus;
import umc.TripPiece.apiPayload.ApiResponse;
import umc.TripPiece.repository.TravelRepository;
import umc.TripPiece.service.TravelService;
import umc.TripPiece.validation.annotation.ExistEntity;
import umc.TripPiece.validation.annotation.ValidateToken;
import umc.TripPiece.web.dto.request.TravelRequestDto;
import umc.TripPiece.web.dto.response.TravelResponseDto;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Tag(name = "Travel", description = "여행기 관련 API")
@RestController
Expand Down Expand Up @@ -75,12 +67,11 @@ public ApiResponse<TravelResponseDto.CreateTripPieceResultDto> createTripPieceMe
@PostMapping("/mytravels/emoji/{travelId}")
@Operation(summary = "이모지 기록 API", description = "특정 여행기에서의 여행조각 추가")
public ApiResponse<TravelResponseDto.CreateTripPieceResultDto> createTripPieceEmoji(
@RequestBody TravelRequestDto.MemoDto request,
@RequestBody TravelRequestDto.EmojiDto request,
@ExistEntity(entityType = umc.TripPiece.domain.Travel.class)
@PathVariable("travelId") Long travelId,
@RequestParam(name = "emojis") List<String> emojis){
@PathVariable("travelId") Long travelId){

TripPiece tripPiece = travelService.createEmoji(travelId, emojis, request);
TripPiece tripPiece = travelService.createEmoji(travelId, request);
return ApiResponse.onSuccess(TravelConverter.toCreateTripPieceResultDto(tripPiece));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
@NoArgsConstructor
@AllArgsConstructor
public class MapRequestDto {

private Long userId;

@NotBlank
private String countryCode;

Expand Down
13 changes: 11 additions & 2 deletions src/main/java/umc/TripPiece/web/dto/request/TravelRequestDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class TravelRequestDto {

Expand All @@ -31,4 +31,13 @@ public static class MemoDto {
String description;
}

@Getter
public static class EmojiDto {
@Size(min = 4, max = 4)
List<String> emojis;

@NotBlank
String description;
}

}
5 changes: 5 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ spring:
username: ${DB_USER}
password: ${DB_PASSWORD}

servlet:
multipart:
max-file-size: 500MB
max-request-size: 500MB

jpa:
hibernate:
ddl-auto: update
Expand Down

0 comments on commit 9eef79c

Please sign in to comment.