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

[Fix/meal create] 식사 도메인 내 API 수정 #46

Merged
merged 7 commits into from
Oct 22, 2023
Merged
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
42 changes: 42 additions & 0 deletions src/main/java/everymeal/server/global/aop/log/LogAspect.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package everymeal.server.global.aop.log;


import everymeal.server.global.exception.ApplicationException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

private LogTrace logTrace;

@Autowired
public LogAspect(LogTrace logTrace) {
this.logTrace = logTrace;
}

@Around("everymeal.server.global.aop.log.Pointcuts.allService()")
public Object executingTimeLog(ProceedingJoinPoint joinPoint) throws Throwable {
TraceInfo traceInfo = null;
try {
traceInfo = logTrace.start(joinPoint.getSignature().toShortString());
Object result = joinPoint.proceed();
logTrace.end(traceInfo);
return result;
} catch (ApplicationException e) {
if (traceInfo != null) {
logTrace.apiException(e, traceInfo);
}
throw e;
} catch (Exception e) {
if (traceInfo != null) {
logTrace.exception(e, traceInfo);
}
throw e;
}
}
}
89 changes: 89 additions & 0 deletions src/main/java/everymeal/server/global/aop/log/LogTrace.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package everymeal.server.global.aop.log;


import everymeal.server.global.exception.ApplicationException;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class LogTrace {

private ThreadLocal<String> threadId = ThreadLocal.withInitial(this::createThreadId);

public TraceInfo start(String method) {
syncTrace();
String id = threadId.get();
long startTime = System.currentTimeMillis();
logger().info("[" + id + "] " + method + " ==== start");
return new TraceInfo(id, method, startTime);
}

public void end(TraceInfo traceInfo) {
long endTime = System.currentTimeMillis();
long resultTime = endTime - traceInfo.startTime();
if (resultTime >= 1000)
logger().warn(
"["
+ traceInfo.theadId()
+ "] "
+ traceInfo.method()
+ " ==== execute time = "
+ resultTime
+ "ms");
else
logger().info(
"["
+ traceInfo.theadId()
+ "] "
+ traceInfo.method()
+ " ==== execute time = "
+ resultTime
+ "ms");
removeThreadLocal();
}

public void apiException(ApplicationException e, TraceInfo traceInfo) {
logger().error(
"["
+ traceInfo.theadId()
+ "] "
+ traceInfo.method()
+ " ==== API EXCEPTION! ["
+ e.getErrorCode()
+ "] "
+ e.getMessage());
removeThreadLocal();
}

public void exception(Exception e, TraceInfo traceInfo) {
logger().error(
"["
+ traceInfo.theadId()
+ "] "
+ traceInfo.method()
+ " ==== INTERNAL ERROR! "
+ e.getMessage());
removeThreadLocal();
}

private void syncTrace() {
String id = threadId.get();
if (id == null) {
threadId.set(createThreadId());
}
}

private String createThreadId() {
return UUID.randomUUID().toString().substring(0, 8);
}

private void removeThreadLocal() {
threadId.remove();
}

private Logger logger() {
return LoggerFactory.getLogger(LogTrace.class);
}
}
17 changes: 17 additions & 0 deletions src/main/java/everymeal/server/global/aop/log/Pointcuts.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package everymeal.server.global.aop.log;


import org.aspectj.lang.annotation.Pointcut;

public class Pointcuts {

@Pointcut("execution(* everymeal.server.meal.*.*(..))")
public void all() {}

@Pointcut("execution(* everymeal.server..*Service.*(..))")
public void allService() {}

@Pointcut(
"execution(* everymeal.server..*Repository.*(..)) || execution(* everymeal.server..*RepositoryImpl.*(..))")
public void allQuery() {}
}
3 changes: 3 additions & 0 deletions src/main/java/everymeal/server/global/aop/log/TraceInfo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package everymeal.server.global.aop.log;

public record TraceInfo(String theadId, String method, Long startTime) {}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package everymeal.server.global.config;


import com.querydsl.jpa.JPQLTemplates;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
Expand All @@ -14,6 +15,6 @@ public class QueryDslConfig {

@Bean
public JPAQueryFactory jpaQueryFactory(EntityManager em) {
return new JPAQueryFactory(em);
return new JPAQueryFactory(JPQLTemplates.DEFAULT, em);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public enum ExceptionList {
RESTAURANT_NOT_FOUND("M0002", HttpStatus.NOT_FOUND, "등록된 식당이 아닙니다."),
UNIVERSITY_NOT_FOUND("M0003", HttpStatus.NOT_FOUND, "등록된 학교가 아닙니다."),
INVALID_MEAL_OFFEREDAT_REQUEST(
"M0004", HttpStatus.BAD_REQUEST, "등록되어 있는 식단 데이터 보다 과거의 날짜로 등록할 수 없습니다."),
"M0004", HttpStatus.BAD_REQUEST, "동일한 데이터를 갖는 식단 데이터가 이미 존재합니다."),
INVALID_REQUEST("R0001", HttpStatus.BAD_REQUEST, "Request의 Data Type이 올바르지 않습니다."),

USER_NOT_FOUND("U0001", HttpStatus.NOT_FOUND, "등록된 유저가 아닙니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ public ApplicationResponse<List<DayMealListGetRes>> getDayMeal(
/**
* 주간 단위 식단 조회 API
*
* @param
* @param restaurantIdx 식당 아이디
* @param offeredAt 조회날짜
* @author dldmsql
*/
@GetMapping("/week")
@Operation(summary = "주간 식단 조회")
Expand All @@ -108,6 +110,6 @@ public ApplicationResponse<List<WeekMealListGetRes>> getWeekMeal(
description = "조회하고자 하는 시작 날짜 ( yyyy-MM-dd )",
defaultValue = "2023-10-01")
String offeredAt) {
return ApplicationResponse.ok(mealService.getWeekMealList(restaurantIdx, offeredAt));
return ApplicationResponse.ok(mealService.getWeekMealListTest(restaurantIdx, offeredAt));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@


import io.swagger.v3.oas.annotations.media.Schema;
import java.time.LocalDate;
import jakarta.validation.constraints.NotBlank;
import java.time.Instant;

public record MealRegisterReq(
@Schema(
description = "메뉴를 ',' 구분자를 기준으로 묶어서 하나의 문자열로 보내주세요.",
defaultValue = "갈비탕, 깍두기, 흰쌀밥")
@NotBlank
String menu,
@Schema(description = "식사 분류 ( 조식 | 중식 | 석식 | 특식 ) ENUM으로 관리합니다.", defaultValue = "LUNCH")
@Schema(
description = "식사 분류 ( BREAKFAST | LUNCH | DINNER ) ENUM으로 관리합니다.",
defaultValue = "LUNCH")
@NotBlank
String mealType,
@Schema(description = "식사 운영 상태 ( 운영 | 미운영 | 단축운영 )", defaultValue = "OPEN")
@Schema(description = "식사 운영 상태 ( OPEN | CLOSED | SHORT_OPEN )", defaultValue = "OPEN")
String mealStatus,
@Schema(description = "식사 제공 날짜 ( yyyy-MM-dd ) ", defaultValue = "2023-10-01")
LocalDate offeredAt,
@Schema(description = "가격을 Double 형태로 관리합니다.", defaultValue = "10000.0") Double price) {}
@Schema(description = "식사 제공 날짜 ( yyyy-MM-dd ) ", defaultValue = "2023-10-01") @NotBlank
Instant offeredAt,
@Schema(description = "가격을 Double 형태로 관리합니다.", defaultValue = "0.0") Double price,
@Schema(
description =
"음식의 카테고리 ( DEFAULT | KOREAN | JAPANESE | CHINESE | SNACKBAR | WESTERN ) 중 단일 메뉴라면 DEFAULT를 입력해주세요.",
defaultValue = "DEFAULT")
@NotBlank
String category) {}
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@


import com.fasterxml.jackson.annotation.JsonFormat;
import everymeal.server.meal.entity.Meal;
import everymeal.server.meal.entity.MealCategory;
import everymeal.server.meal.entity.MealStatus;
import everymeal.server.meal.entity.MealType;
import java.time.LocalDate;
import java.util.List;
import java.time.Instant;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
Expand All @@ -21,21 +24,9 @@ public class DayMealListGetRes {
private MealStatus mealStatus;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Asia/Seoul")
private LocalDate offeredAt;
private Instant offeredAt;

private Double price;

public static List<DayMealListGetRes> of(List<Meal> mealList) {
return mealList.stream()
.map(
meal ->
DayMealListGetRes.builder()
.menu(meal.getMenu())
.mealType(meal.getMealType())
.mealStatus(meal.getMealStatus())
.offeredAt(meal.getOfferedAt())
.price(meal.getPrice())
.build())
.toList();
}
private MealCategory category;
private String restaurantName;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,28 @@


import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import com.querydsl.core.annotations.QueryProjection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@Builder
public class WeekMealListGetRes {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "Asia/Seoul")
private LocalDate offeredAt;
private Instant offeredAt;

private List<DayMealListGetRes> dayMealListGetResList;
private List<DayMealListGetRes> dayMealListGetResListTest;

public static List<WeekMealListGetRes> of(List<DayMealListGetRes> mealListGetRes) {
// offeredAt을 기준으로 DayMealList 그룹핑
Map<LocalDate, List<DayMealListGetRes>> groupedData =
mealListGetRes.stream()
.collect(Collectors.groupingBy(DayMealListGetRes::getOfferedAt));
List<WeekMealListGetRes> weekMealList = new ArrayList<>();
for (Map.Entry<LocalDate, List<DayMealListGetRes>> entry : groupedData.entrySet()) {
WeekMealListGetRes weekMeal =
WeekMealListGetRes.builder()
.offeredAt(entry.getKey())
.dayMealListGetResList(entry.getValue())
.build();
weekMealList.add(weekMeal);
}
// offeredAt을 기준으로 오름차순 정렬
weekMealList.sort(Comparator.comparing(WeekMealListGetRes::getOfferedAt));
return weekMealList;
@QueryProjection
public WeekMealListGetRes(
Instant offeredAt, List<DayMealListGetRes> dayMealListGetResListTest) {
this.offeredAt = offeredAt;
this.dayMealListGetResListTest = dayMealListGetResListTest;
}
}
17 changes: 13 additions & 4 deletions src/main/java/everymeal/server/meal/entity/Meal.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Index;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import java.time.LocalDate;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
import java.time.Instant;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@Table
@Table(indexes = {@Index(name = "idx__mealType__offeredAt", columnList = "mealType, offeredAt")})
@Entity
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
public class Meal {
Expand All @@ -32,25 +35,31 @@ public class Meal {
@Enumerated(EnumType.STRING)
private MealStatus mealStatus;

private LocalDate offeredAt;
@Temporal(TemporalType.TIMESTAMP)
private Instant offeredAt;

private Double price;

@Enumerated(EnumType.STRING)
private MealCategory category;

@ManyToOne private Restaurant restaurant;

@Builder
public Meal(
String menu,
MealType mealType,
MealStatus mealStatus,
LocalDate offeredAt,
Instant offeredAt,
Double price,
MealCategory category,
Restaurant restaurant) {
this.menu = menu;
this.mealType = mealType;
this.mealStatus = mealStatus;
this.offeredAt = offeredAt;
this.price = price;
this.category = category;
this.restaurant = restaurant;
}
}
Loading
Loading