Skip to content

Commit

Permalink
feat: 유효한 주소인지 확인하고 우편번호 반환하는 api 기능 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
summit45 committed Nov 14, 2023
1 parent 39e232f commit 804b14c
Show file tree
Hide file tree
Showing 9 changed files with 112 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ public enum ErrorCode {
//address
REGION_ALREADY_EXISTS_ERROR(false, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 지역입니다."),
REGION_NOT_FOUND_ERROR(false, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 지역입니다."),
GEOCODING_CONNECTION_ERROR(false, HttpStatus.BAD_REQUEST.value(), "지오코딩 서버와 연결할 수 없습니다."),
GEOCODING_INVALID_REQUEST_ERROR(false, HttpStatus.BAD_REQUEST.value(), "지오코딩 서버의 알 수 없는 오류입니다. 다시 요청해주세요."),
GEOCODING_UNKNOWN_ADDRESS_ERROR(false, HttpStatus.BAD_REQUEST.value(), "찾을 수 없는 주소입니다. 주소를 다시 확인해주세요."),
GEOCODING_QUERY_MISSING_ERROR(false, HttpStatus.BAD_REQUEST.value(), "지오코딩 쿼리가 없습니다. 다시 요청해주세요.")
;

private Boolean isSuccess;
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/kusitms/jipbap/user/UserAddressController.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package com.kusitms.jipbap.user;

import com.kusitms.jipbap.common.response.CommonResponse;
import com.kusitms.jipbap.user.dto.address.GlobalRegionRequest;
import com.kusitms.jipbap.user.dto.address.GlobalRegionResponse;
import com.kusitms.jipbap.user.dto.address.UserAddressRequest;
import com.kusitms.jipbap.user.dto.address.UserAddressResponse;
import com.kusitms.jipbap.user.dto.address.*;
import com.kusitms.jipbap.user.entity.GlobalRegion;
import com.kusitms.jipbap.user.repository.GlobalRegionRepository;
import io.swagger.v3.oas.annotations.Operation;
Expand All @@ -29,6 +26,13 @@ public CommonResponse<UserAddressResponse> saveUserAddress(@Valid @RequestBody U
return new CommonResponse<>(userAddressService.saveUserAddress(dto));
}

@Operation(summary = "유효한 주소인지 확인하고 우편번호 반환하기")
@GetMapping("/valid")
@ResponseStatus(HttpStatus.OK)
public CommonResponse<PostalAddressDto> getValidPostalCode(@RequestParam String address) {
return new CommonResponse<>(userAddressService.getValidPostalCode(address));
}

@Operation(summary = "지역 코드 데이터 저장하기")
@PostMapping("/global-area")
@ResponseStatus(HttpStatus.CREATED)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import com.kusitms.jipbap.common.response.CommonResponse;
import com.kusitms.jipbap.common.response.ErrorCode;
import com.kusitms.jipbap.user.exception.RegionNotFoundException;
import com.kusitms.jipbap.user.exception.RegionExistsException;
import com.kusitms.jipbap.user.exception.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
Expand All @@ -27,4 +26,32 @@ public CommonResponse<?> RegionNotFoundException(RegionNotFoundException e, Http
log.warn("UserAddress-002> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new CommonResponse<>(ErrorCode.REGION_NOT_FOUND_ERROR);
}

@ExceptionHandler(GeocodingConnectionException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CommonResponse<?> GeocodingConnectionException(GeocodingConnectionException e, HttpServletRequest request) {
log.warn("UserAddress-003> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new CommonResponse<>(ErrorCode.GEOCODING_CONNECTION_ERROR);
}

@ExceptionHandler(GeocodingUnknownAddressException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CommonResponse<?> GeocodingUnknownAddressException(GeocodingUnknownAddressException e, HttpServletRequest request) {
log.warn("UserAddress-004> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new CommonResponse<>(ErrorCode.GEOCODING_UNKNOWN_ADDRESS_ERROR);
}

@ExceptionHandler(GeocodingInvalidRequestException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CommonResponse<?> GeocodingInvalidRequestException(GeocodingInvalidRequestException e, HttpServletRequest request) {
log.warn("UserAddress-005> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new CommonResponse<>(ErrorCode.GEOCODING_INVALID_REQUEST_ERROR);
}

@ExceptionHandler(GeocodingQueryMissingException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public CommonResponse<?> GeocodingQueryMissingException(GeocodingQueryMissingException e, HttpServletRequest request) {
log.warn("UserAddress-006> 요청 URI: " + request.getRequestURI() + ", 에러 메세지: " + e.getMessage());
return new CommonResponse<>(ErrorCode.GEOCODING_QUERY_MISSING_ERROR);
}
}
59 changes: 28 additions & 31 deletions src/main/java/com/kusitms/jipbap/user/UserAddressService.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package com.kusitms.jipbap.user;

import com.kusitms.jipbap.user.dto.address.GlobalRegionRequest;
import com.kusitms.jipbap.user.dto.address.GlobalRegionResponse;
import com.kusitms.jipbap.user.dto.address.UserAddressRequest;
import com.kusitms.jipbap.user.dto.address.UserAddressResponse;
import com.kusitms.jipbap.user.dto.address.*;
import com.kusitms.jipbap.user.dto.geolocation.AddressComponentDto;
import com.kusitms.jipbap.user.dto.geolocation.GeocodingAddressDto;
import com.kusitms.jipbap.user.dto.geolocation.GeocodingResponseDto;
Expand All @@ -12,7 +9,6 @@
import com.kusitms.jipbap.user.repository.GlobalRegionRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -35,7 +31,7 @@ public class UserAddressService {
@Transactional
public UserAddressResponse saveUserAddress(UserAddressRequest dto) {
User user = userRepository.findById(dto.getUserId())
.orElseThrow(()-> new UserNotFoundException("유저 정보가 존재하지 않습니다."));
.orElseThrow(() -> new UserNotFoundException("유저 정보가 존재하지 않습니다."));
GlobalRegion globalRegion = globalRegionRepository.findById(dto.getGlobalRegionId())
.orElseThrow(() -> new RegionNotFoundException("지역 정보가 존재하지 않습니다."));

Expand All @@ -45,7 +41,8 @@ public UserAddressResponse saveUserAddress(UserAddressRequest dto) {
}

public GlobalRegionResponse saveGlobalAreaData(GlobalRegionRequest dto) {
if(globalRegionRepository.existsByRegionName(dto.getRegionName())) throw new RegionExistsException("이미 존재하는 지역입니다.");
if (globalRegionRepository.existsByRegionName(dto.getRegionName()))
throw new RegionExistsException("이미 존재하는 지역입니다.");

GlobalRegion globalRegion = globalRegionRepository.save(dto.toEntity());
return new GlobalRegionResponse(globalRegion);
Expand All @@ -62,11 +59,11 @@ public List<GlobalRegionResponse> getAllGlobalAreaData() {
}

@Transactional
public void getGeoDataByAddress(String address){
JSONObject geocodingData = getGeocodingData(address);
public PostalAddressDto getValidPostalCode(String address) {
return getGeocodingData(address);
}

private JSONObject getGeocodingData(String address) {
private PostalAddressDto getGeocodingData(String address) {
try {
String apiUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + apiKey;

Expand All @@ -75,27 +72,25 @@ private JSONObject getGeocodingData(String address) {
//String response = restTemplate.getForObject(apiUrl, String.class);
log.info("{} 주소에 대한 getGeocodingData API response 결과 : {} ", address, responseDto.getStatus());

if ("OK".equals(responseDto.getStatus())) {
saveUserAddress(responseDto.getResults().get(0));
} else if ("ZERO_RESULTS".equals(responseDto.getStatus())){
throw new GeocodingUnknownAdressException("주소가 존재하지 않습니다.");
} else if ("OVER_DAILY_LIMIT".equals(responseDto.getStatus())) {
throw new GeocodingConnectionException("API키가 잘못되었거나 결제가 사용 설정 되지 않았습니다.");
} else if ("OVER_QUERY_LIMIT".equals(responseDto.getStatus())) {
throw new GeocodingConnectionException("할당량이 초과되었습니다.");
} else if ("REQUEST_DENIED".equals(responseDto.getStatus())) {
throw new GeocodingConnectionException("요청이 거부되었습니다.");
} else if ("INVALID_REQUEST".equals(responseDto.getStatus())) {
throw new GeocodingUnknownAdressException("쿼리가 누락되었습니다.");
} else if ("UNKNOWN_ERROR".equals(responseDto.getStatus())) {
throw new GeocodingConnectionException("서버 에러입니다.");
} else {
throw new GeocodingConnectionException("그 외의 오류가 발생했습니다.");
switch (responseDto.getStatus()) {
case "OK":
return findPostalAddress(responseDto.getResults().get(0));
case "ZERO_RESULTS":
throw new GeocodingUnknownAddressException("주소가 존재하지 않습니다.");
case "OVER_DAILY_LIMIT":
case "OVER_QUERY_LIMIT":
case "REQUEST_DENIED":
throw new GeocodingConnectionException("API키가 잘못되었거나 결제가 사용 설정 되지 않았습니다.");
case "INVALID_REQUEST":
throw new GeocodingQueryMissingException("쿼리가 누락되었습니다.");
case "UNKNOWN_ERROR":
throw new GeocodingUnknownAddressException("알 수 없는 지오코딩 에러입니다.");
default:
throw new GeocodingConnectionException("서버 에러입니다.");
}
return new JSONObject(responseDto);
} catch (Exception e) {
e.printStackTrace();
return null;
//e.printStackTrace();
throw e;
}
}

Expand All @@ -106,7 +101,7 @@ private void setUserData(User user, GlobalRegion globalRegion, UserAddressReques
user.setPostalCode(dto.getPostalCode());
}

private void saveUserAddress(GeocodingAddressDto geocodingAddressDto) {
private PostalAddressDto findPostalAddress(GeocodingAddressDto geocodingAddressDto) {
try {
String formattedAddress = geocodingAddressDto.getFormattedAddress(); // 실제 데이터베이스에 저장할 주소

Expand All @@ -121,11 +116,13 @@ private void saveUserAddress(GeocodingAddressDto geocodingAddressDto) {
countryName = addressComponent.getLongName();
}
if (types != null && types.contains("postal_code")) {
postalCode= addressComponent.getLongName();
postalCode = addressComponent.getLongName();
}
}
return new PostalAddressDto(formattedAddress, postalCode);
} catch (NullPointerException e) {
e.printStackTrace();
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.kusitms.jipbap.user.dto.address;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class PostalAddressDto {
String formattedAddress;
String postalCode;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kusitms.jipbap.user.exception;

public class GeocodingConnectionException extends RuntimeException {
public GeocodingConnectionException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kusitms.jipbap.user.exception;

public class GeocodingInvalidRequestException extends RuntimeException {
public GeocodingInvalidRequestException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kusitms.jipbap.user.exception;

public class GeocodingQueryMissingException extends RuntimeException {
public GeocodingQueryMissingException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kusitms.jipbap.user.exception;

public class GeocodingUnknownAddressException extends RuntimeException {
public GeocodingUnknownAddressException(String message) {
super(message);
}
}

0 comments on commit 804b14c

Please sign in to comment.