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

8주차 미션 / 서버 1조 김경민 #24

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package kuit.server.common.exception;

import kuit.server.common.response.status.ResponseStatus;
import lombok.Getter;

@Getter
public class RestaurantException extends RuntimeException{
private final ResponseStatus exceptionStatus;

public RestaurantException(ResponseStatus exceptionStatus) {
super(exceptionStatus.getMessage());
this.exceptionStatus = exceptionStatus;
}

public RestaurantException(ResponseStatus exceptionStatus, String message) {
super(message);
this.exceptionStatus = exceptionStatus;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package kuit.server.common.exception_handler;

import jakarta.annotation.Priority;
import kuit.server.common.exception.RestaurantException;
import kuit.server.common.response.BaseErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static kuit.server.common.response.status.BaseExceptionResponseStatus.INVALID_RESTAURANT_VALUE;

@Slf4j
@Priority(0)
@RestControllerAdvice
public class RestaurantExceptionControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(RestaurantException.class)
public BaseErrorResponse handle_RestaurantException(RestaurantException e) {
log.error("[handle_RestaurantException]", e);
return new BaseErrorResponse(e.getExceptionStatus(), e.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class UserExceptionControllerAdvice {
@ExceptionHandler(UserException.class)
public BaseErrorResponse handle_UserException(UserException e) {
log.error("[handle_UserException]", e);
return new BaseErrorResponse(INVALID_USER_VALUE, e.getMessage());
return new BaseErrorResponse(e.getExceptionStatus(), e.getMessage());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,20 @@ public enum BaseExceptionResponseStatus implements ResponseStatus {
*/
INVALID_USER_VALUE(5000, HttpStatus.BAD_REQUEST.value(), "회원가입 요청에서 잘못된 값이 존재합니다."),
DUPLICATE_EMAIL(5001, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 이메일입니다."),
DUPLICATE_NICKNAME(5002, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 닉네임입니다."),
USER_NOT_FOUND(4003, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 회원입니다."),
PASSWORD_NO_MATCH(4004, HttpStatus.BAD_REQUEST.value(), "비밀번호가 일치하지 않습니다."),
INVALID_USER_STATUS(4005, HttpStatus.BAD_REQUEST.value(), "잘못된 회원 status 값입니다."),
EMAIL_NOT_FOUND(4006, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 이메일입니다.");
DUPLICATE_NAME(5002, HttpStatus.BAD_REQUEST.value(), "이미 존재하는 이름입니다."),
USER_NOT_FOUND(5003, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 회원입니다."),
PASSWORD_NO_MATCH(5004, HttpStatus.BAD_REQUEST.value(), "비밀번호가 일치하지 않습니다."),
INVALID_USER_STATUS(5005, HttpStatus.BAD_REQUEST.value(), "잘못된 회원 status 값입니다."),
EMAIL_NOT_FOUND(5006, HttpStatus.BAD_REQUEST.value(), "존재하지 않는 이메일입니다."),

/**
* 6000: Restaurant 오류
*/
INVALID_RESTAURANT_VALUE(6000,HttpStatus.BAD_REQUEST.value(),"식당등록 요청에서 잘못된 값이 존재합니다."),
DUPLICATE_PHONE(6001,HttpStatus.BAD_REQUEST.value(),"이미 존재하는 전화번호입니다."),
INVALID_RESTAURANT_STATUS(6002,HttpStatus.BAD_REQUEST.value(),"잘못된 식당 status입니다."),
RESTAURANT_NOT_FOUND(6003,HttpStatus.BAD_REQUEST.value(),"존재하지 않는 식당입니다.");


private final int code;
private final int status;
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/kuit/server/controller/ResponseController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package kuit.server.controller;

import kuit.server.common.response.BaseErrorResponse;
import kuit.server.common.response.BaseResponse;
import kuit.server.temp.UserData;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static kuit.server.common.response.status.BaseExceptionResponseStatus.BAD_REQUEST;

@RestController
public class ResponseController {
@RequestMapping("/base-response")
public BaseResponse<UserData> getSuccessResponse() {
UserData userData = new UserData("kim", 20);
return new BaseResponse<>(userData);
}

@RequestMapping("/base-error-response")
public BaseErrorResponse getErrorResponse() {
return new BaseErrorResponse(BAD_REQUEST);
}
}
89 changes: 89 additions & 0 deletions src/main/java/kuit/server/controller/RestaurantController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package kuit.server.controller;

import kuit.server.common.exception.UserException;
import kuit.server.common.response.BaseResponse;
import kuit.server.dto.restaurant.GetRestaurantResponse;
import kuit.server.dto.restaurant.PostRestaurantRequest;
import kuit.server.service.RestaurantService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static kuit.server.common.response.status.BaseExceptionResponseStatus.INVALID_RESTAURANT_STATUS;
import static kuit.server.common.response.status.BaseExceptionResponseStatus.INVALID_RESTAURANT_VALUE;
import static kuit.server.util.BindingResultUtils.getErrorMessages;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/restaurant")
public class RestaurantController {

private final RestaurantService restaurantService;

/**
* 레스토랑 등록
*/
@PostMapping("")
public BaseResponse<Long> createRestaurant(@Validated @RequestBody PostRestaurantRequest postRestaurantRequest, BindingResult bindingResult) {
log.info("[RestaurantController.registerRestaurant]");
if (bindingResult.hasErrors()) {
throw new UserException(INVALID_RESTAURANT_VALUE, getErrorMessages(bindingResult));
}
long restaurantId = restaurantService.createRestaurant(postRestaurantRequest);
return new BaseResponse<>(restaurantId);
}

/**
* 레스토랑 상태 수정
*/
@PatchMapping("/{restaurantid}/status")
public BaseResponse<Object> modifyRestaurantStatus(@PathVariable long restaurantid, @RequestParam String status) {
log.info("[RestaurantController.modifyRestaurantStatus]");
restaurantService.updateRestaurantStatus(restaurantid, status);
return new BaseResponse<>(null);
}

/**
* 레스토랑 정보 수정
*/
@PutMapping("/{restaurantid}")
public BaseResponse<Object> modifyRestaurantDetails(@PathVariable long restaurantid,
@Validated @RequestBody PostRestaurantRequest postRestaurantRequest,
BindingResult bindingResult) {
log.info("[RestaurantController.modifyRestaurantDetails]");
if (bindingResult.hasErrors()) {
throw new UserException(INVALID_RESTAURANT_VALUE, getErrorMessages(bindingResult));
}
restaurantService.updateRestaurantDetails(restaurantid, postRestaurantRequest);
return new BaseResponse<>(null);
}

/**
* 레스토랑 목록 조회
*/
@GetMapping("")
public BaseResponse<List<GetRestaurantResponse>> getRestaurants(
@RequestParam(required = false, defaultValue = "") String name,
@RequestParam(required = false, defaultValue = "") String location,
@RequestParam(required = false, defaultValue = "Open") String status) {
log.info("[RestaurantController.getRestaurants]");
if (!status.equals("Close") && !status.equals("Open")) {
throw new UserException(INVALID_RESTAURANT_STATUS);
}
return new BaseResponse<>(restaurantService.getRestaurants(name, location, status));
}

/**
* 레스토랑 ID로 레스토랑 조회
*/
@GetMapping("/{restaurantid}")
public BaseResponse<GetRestaurantResponse> getRestaurantById(@PathVariable long restaurantid) {
log.info("[RestaurantController.getRestaurantById]");
return new BaseResponse<>(restaurantService.getRestaurantById(restaurantid));
}
}
16 changes: 11 additions & 5 deletions src/main/java/kuit/server/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ public BaseResponse<PostUserResponse> signUp(@Validated @RequestBody PostUserReq
return new BaseResponse<>(userService.signUp(postUserRequest));
}

@PostMapping("/login")
public BaseResponse<PostLoginResponse> logIn(@RequestBody PostLoginRequest postLoginReq) {
log.info("MemberController.login");
return new BaseResponse<>(userService.logIn(postLoginReq));
}

/**
* 회원 휴면
*/
Expand All @@ -59,14 +65,14 @@ public BaseResponse<Object> modifyUserStatus_deleted(@PathVariable long userId)
/**
* 닉네임 변경
*/
@PatchMapping("/{userId}/nickname")
public BaseResponse<String> modifyNickname(@PathVariable long userId,
@Validated @RequestBody PatchNicknameRequest patchNicknameRequest, BindingResult bindingResult) {
log.info("[UserController.modifyNickname]");
@PatchMapping("/{userId}/name")
public BaseResponse<String> modifyName(@PathVariable long userId,
@Validated @RequestBody PatchNameRequest patchNameRequest, BindingResult bindingResult) {
log.info("[UserController.modifyName]");
if (bindingResult.hasErrors()) {
throw new UserException(INVALID_USER_VALUE, getErrorMessages(bindingResult));
}
userService.modifyNickname(userId, patchNicknameRequest.getNickname());
userService.modifyName(userId, patchNameRequest.getName());
return new BaseResponse<>(null);
}

Expand Down
114 changes: 114 additions & 0 deletions src/main/java/kuit/server/dao/RestaurantDao.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package kuit.server.dao;

import kuit.server.dto.restaurant.PostRestaurantRequest;
import kuit.server.dto.restaurant.RestaurantDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Repository
public class RestaurantDao {
private final NamedParameterJdbcTemplate jdbcTemplate;

public RestaurantDao(DataSource dataSource) {
this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
// 레스토랑 생성
public long createRestaurant(PostRestaurantRequest postRestaurantRequest) {
String sql = "insert into Restaurant(name, location, phone, category, min_order_amount, status) " +
"values(:name, :location, :phone, :category, :minOrderAmount, :status)";

SqlParameterSource param = new BeanPropertySqlParameterSource(postRestaurantRequest);
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(sql, param, keyHolder);

return Objects.requireNonNull(keyHolder.getKey()).longValue();
}

// 레스토랑 상태 변경
public int modifyRestaurantStatus(long restaurantid, String status) {
String sql = "update Restaurant set status=:status where restaurantid=:restaurantid";
Map<String, Object> param = Map.of(
"status", status,
"restaurantid", restaurantid);
return jdbcTemplate.update(sql, param);
}
// 디테일 스정
public int modifyRestaurantDetails(long restaurantid, String name, String location, String phone, String category, int minOrderAmount) {
String sql = "update Restaurant set name=:name, location=:location, phone=:phone, category=:category, min_order_amount=:minOrderAmount where restaurantid=:restaurantid";
Map<String, Object> param = Map.of(
"name", name,
"location", location,
"phone", phone,
"category", category,
"minOrderAmount", minOrderAmount,
"restaurantid", restaurantid);
return jdbcTemplate.update(sql, param);
}
public List<RestaurantDto> getRestaurants(String name, String location, String status) {
String sql = "select restaurantid, name, location, phone, category, min_order_amount, status from Restaurant " +
"where name like :name and location like :location";

Map<String, Object> param = Map.of(
"name", "%" + name + "%",
"location", "%" + location + "%"
);

if (status != null && !status.isEmpty()) {
sql += " and status = :status";
param = new HashMap<>(param);
param.put("status", status);
}

return jdbcTemplate.query(sql, param,
(rs, rowNum) -> new RestaurantDto(
rs.getLong("restaurantid"),
rs.getString("name"),
rs.getString("location"),
rs.getString("phone"),
rs.getString("category"),
rs.getInt("min_order_amount"),
rs.getString("status"))
);
}


public RestaurantDto getRestaurantById(long restaurantid) {
String sql = "select restaurantid, name, location, phone, category, min_order_amount, status from Restaurant where restaurantid=:restaurantid";
Map<String, Object> param = Map.of("restaurantid", restaurantid);
return jdbcTemplate.queryForObject(sql, param,
(rs, rowNum) -> new RestaurantDto(
rs.getLong("restaurantid"),
rs.getString("name"),
rs.getString("location"),
rs.getString("phone"),
rs.getString("category"),
rs.getInt("min_order_amount"),
rs.getString("status"))
);
}

public long getRestaurantIdByName(String name) {
String sql = "select restaurantid from Restaurant where name=:name";
Map<String, Object> param = Map.of("name", name);
return jdbcTemplate.queryForObject(sql, param, Long.class);
}


public boolean hasDuplicatePhone(String phone) {
String sql = "select exists(select phone from restaurant where phone=:phone)";
Map<String, Object> param = Map.of("phone", phone);
return Boolean.TRUE.equals(jdbcTemplate.queryForObject(sql, param, Boolean.class));
}
}
Loading