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

Develop #60

Merged
merged 13 commits into from
Apr 30, 2024
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ protected boolean shouldNotFilter(HttpServletRequest request) {
skipPathList.add(new AntPathRequestMatcher("/api/auth/token/refresh", HttpMethod.POST.name()));
skipPathList.add(new AntPathRequestMatcher("/api/oauth/kakao", HttpMethod.GET.name()));
skipPathList.add(new AntPathRequestMatcher("/api/weather", HttpMethod.GET.name()));
skipPathList.add(new AntPathRequestMatcher("/api/posts/**", HttpMethod.GET.name()));
skipPathList.add(new AntPathRequestMatcher("/api/posts", HttpMethod.POST.name()));
skipPathList.add(new AntPathRequestMatcher("/api/posts", HttpMethod.PUT.name()));
skipPathList.add(new AntPathRequestMatcher("/api/posts", HttpMethod.DELETE.name()));
skipPathList.add(new AntPathRequestMatcher("/api/posts/*/likes", HttpMethod.GET.name()));
skipPathList.add(new AntPathRequestMatcher("/api/posts/*/reviews", HttpMethod.GET.name()));

skipPathList.add(new AntPathRequestMatcher("/api/districts/**", HttpMethod.GET.name()));
skipPathList.add(new AntPathRequestMatcher("/h2-console/**"));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
filterChain.doFilter(request, response);
} catch (BusinessException e) {
errorLoggerHelper.log(wrapper, e.getErrorType(), e.getMessage());
e.printStackTrace();
setErrorResponse(e.getErrorType(), e.getMessage(), response);
} catch (Exception e) {
errorLoggerHelper.log(wrapper, ErrorType.INTERNAL_ERROR, e.getMessage());
e.printStackTrace();
setErrorResponse(ErrorType.INTERNAL_ERROR, "서버 에러 ", response);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public Authentication getAuthentication(String token) {
Collections.singleton(new SimpleGrantedAuthority("ROLE_MEMBER"));

return new UsernamePasswordAuthenticationToken(
new User(claims.getSubject(), "", authorities), token, authorities
new User(claims.get("id").toString(), "", authorities), token, authorities
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@
@Getter
@AllArgsConstructor
public class AuthMember {

private String email;
private Long id;
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ public boolean supportsParameter(MethodParameter parameter) {
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = (User) authentication.getPrincipal();
return new AuthMember(user.getUsername());

return new AuthMember(Long.parseLong(user.getUsername()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,31 +29,36 @@ public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<?> handleBusinessException(BusinessException e, RequestWrapper request) throws IOException {
errorLoggerHelper.log(request, e.getErrorType(), e.getMessage());
e.printStackTrace();
return ApiResponse.fail(e.getErrorType(), e.getMessage());
}

@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<?> handleConstraintViolationException(ConstraintViolationException e, RequestWrapper request) throws IOException {
errorLoggerHelper.log(request, ErrorType.INVALID_INPUT_VALUE, e.getMessage());
e.printStackTrace();
return ApiResponse.fail(ErrorType.INVALID_INPUT_VALUE, "잘못된 값입니다.");
}

@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<?> handleEntityNotFoundException(EntityNotFoundException e, RequestWrapper request) throws IOException {
errorLoggerHelper.log(request, ErrorType.ENTITY_NOT_FOUND, e.getMessage());
e.printStackTrace();
return ApiResponse.fail(ErrorType.ENTITY_NOT_FOUND, e.getMessage());
}

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleIllegalArgumentException(MethodArgumentNotValidException e, RequestWrapper request) throws IOException {
errorLoggerHelper.log(request, ErrorType.INVALID_INPUT_VALUE, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
e.printStackTrace();
return ApiResponse.fail(ErrorType.INVALID_INPUT_VALUE, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
}

// 기타 예외 처리
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception e, RequestWrapper request) throws IOException {
errorLoggerHelper.log(request, ErrorType.INTERNAL_ERROR, e.getMessage());
e.printStackTrace();
return ApiResponse.fail(ErrorType.INTERNAL_ERROR, "내부 서버 오류가 발생했습니다.");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,10 @@ public static ResponseEntity<?> ok(String message){
}

public static ResponseEntity<?> ok(String message, Object data){
if (data instanceof Collection && ((Collection<?>) data).isEmpty()) {
return noContent(message); // 데이터가 없을 때 적절한 응답 반환
}
SuccessResponse response = new SuccessResponse(message, data);
return ResponseEntity.ok(response);
}

public static ResponseEntity<?> noContent(String message) {
// HTTP 204 No Content 상태와 함께 메시지 반환
return ResponseEntity.noContent().header("X-Message", message).build();
}

public static ResponseEntity<?> fail(ErrorType errorType, String message){
FailResponse response = new FailResponse(message, errorType.getErrorCode());
return ResponseEntity.status(errorType.getStatusCode()).body(response);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,10 @@ public int countByPostId(Long postId) {
return likeRepository.countByPostId(postId);
}

@Override
public boolean existsByPostIdAndMemberId(Long postId, Long memberId) {
return likeRepository.existsByPostIdAndMemberId(postId, memberId);
}


}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.seoultech.sanEseo.like.adapter;

import com.seoultech.sanEseo.global.config.web.AuthMember;
import com.seoultech.sanEseo.global.config.web.LoginMember;
import com.seoultech.sanEseo.global.response.ApiResponse;
import com.seoultech.sanEseo.like.application.service.AddLikeRequest;
import com.seoultech.sanEseo.like.application.service.GetLikeResponse;
Expand All @@ -18,14 +20,14 @@ public LikeController(LikeService likeService) {
}

@PostMapping("/likes")
public ResponseEntity<?> addLike(@RequestBody AddLikeRequest request) {
likeService.addLike(request);
public ResponseEntity<?> addLike(@LoginMember AuthMember member, @RequestBody AddLikeRequest request) {
likeService.addLike(member.getId(), request);
return ApiResponse.ok("좋아요가 추가되었습니다.");
}

@DeleteMapping("/posts/{postId}/members/{memberId}/likes")
public ResponseEntity<?> deleteLike(@PathVariable Long postId, @PathVariable Long memberId) {
likeService.deleteLike(postId, memberId);
@DeleteMapping("/posts/{postId}/members/likes")
public ResponseEntity<?> deleteLike(@LoginMember AuthMember member, @PathVariable Long postId) {
likeService.deleteLike(postId, member.getId());
return ApiResponse.ok("좋아요가 삭제되었습니다.");
}

Expand All @@ -35,4 +37,10 @@ public ResponseEntity<?> getLikeCount(@PathVariable Long postId) {
return ApiResponse.ok("좋아요 수 조회 성공", new GetLikeResponse(postId, likeCount));
}

@GetMapping("/posts/{postId}/members/likes")
public ResponseEntity<?> hasMemberLikedPost(@LoginMember AuthMember authMember, @PathVariable Long postId) {
boolean hasLiked = likeService.hasMemberLikedPost(authMember.getId(), postId);
return ApiResponse.ok("좋아요 여부 조회 성공", hasLiked);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ public interface LikeRepository extends JpaRepository<Likes, Long> {
int countByPostId(Long postId);
void deleteByPostAndMember(Post post, Member member);

boolean existsByPostIdAndMemberId(Long postId, Long memberId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ public interface LikePort {

int countByPostId(Long postId);

boolean existsByPostIdAndMemberId(Long postId, Long memberId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,14 @@


import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class AddLikeRequest {
@NotNull(message = "포스트 ID는 필수입니다.")
private Long postId;

@NotNull(message = "멤버 ID는 필수입니다.")
private Long memberId;

// 모든 매개변수를 가진 생성자
public AddLikeRequest(Long postId, Long memberId) {
this.postId = postId;
this.memberId = memberId;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,10 @@ public class LikeService {



public void addLike(AddLikeRequest request) {
public void addLike(Long memberId, AddLikeRequest request) {

// request를 Like 객체로 변환
Long postId = request.getPostId();
Long memberId = request.getMemberId();

Member member = memberPort.loadById(memberId);
Post post = postPort.getPost(postId);
Expand All @@ -54,4 +53,8 @@ public int getLikeCount(Long postId) {
return likePort.countByPostId(postId);
}

public boolean hasMemberLikedPost(Long memberId, Long postId) {
return likePort.existsByPostIdAndMemberId(memberId, postId);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public ResponseEntity<?> login(@RequestBody LoginRequest request) {

@PostMapping("/logout")
public ResponseEntity<?> logout(@LoginMember AuthMember authMember) {
authService.logout(authMember.getEmail());
authService.logout(authMember.getId());
return ApiResponse.ok("로그아웃 성공");
} // TODO : 로그아웃 구현

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ public ResponseEntity<?> register(@RequestBody RegisterRequest request) {

@PatchMapping
public ResponseEntity<?> updateMember(@LoginMember AuthMember authMember, @ModelAttribute UpdateMemberRequest request) {
return ApiResponse.ok("회원정보 수정 성공", memberService.updateMember(request.toCommand(authMember.getEmail())));
return ApiResponse.ok("회원정보 수정 성공", memberService.updateMember(request.toCommand(authMember.getId())));
}

@GetMapping
public ResponseEntity<?> findMember(@LoginMember AuthMember authMember) {
return ApiResponse.ok("사용자 정보 조회 성공", MemberResponse.fromEntity(memberService.loadMemberByEmail(authMember.getEmail())));
return ApiResponse.ok("사용자 정보 조회 성공", MemberResponse.fromEntity(memberService.loadMember(authMember.getId())));
}

@GetMapping("/duplicate")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@

public record UpdateMemberRequest(String name, MultipartFile profile) {

public UpdateMemberCommand toCommand(String email) {
public UpdateMemberCommand toCommand(Long id) {
return UpdateMemberCommand.builder()
.email(email)
.memberId(id)
.name(name)
.profile(profile)
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
@EqualsAndHashCode(callSuper = false)
public class UpdateMemberCommand{

private final String email;
private final Long memberId;
private final String name;
private final MultipartFile profile;

@Builder
public UpdateMemberCommand(String email, String name, MultipartFile profile) {
this.email = email;
public UpdateMemberCommand(Long memberId, String name, MultipartFile profile) {
this.memberId = memberId;
this.name = name;
this.profile = profile;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ public void register(OAuthRegisterCommand command) {
}

@Transactional
public void logout(String email) {
Member member = memberPort.loadByEmail(email);
public void logout(Long memberId) {
Member member = memberPort.loadById(memberId);
RefreshToken refreshToken = refreshTokenPort.loadByUserId(member.getId());
if(refreshToken == null) {
throw new NotLoginedMemberException("로그인이 되어있지 않습니다.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public String generateName() {

@Transactional
public MemberResponse updateMember(UpdateMemberCommand command) {
Member member = memberPort.loadByEmail(command.getEmail());
Member member = memberPort.loadById(command.getMemberId());

if(command.getName() != null) {
checkDuplicateName(command.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.seoultech.sanEseo.post.domain.Category;
import com.seoultech.sanEseo.image.PostImage;
import com.seoultech.sanEseo.public_api.GetCoordinateResponse;
import com.seoultech.sanEseo.public_api.GetGeometryResponse;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
Expand Down Expand Up @@ -40,9 +42,12 @@ public class AddPostRequest {
@NotNull(message = "자치구 ID는 필수입니다.")
private Long districtId;

@NotNull(message = "좌표 정보는 필수입니다.")
private GetGeometryResponse geometry;

// 생성자, 게터, 세터 등 추가 필요

public AddPostRequest(Category category, String title, String subTitle, String description, String level, String time, String distance, String courseDetail, String transportation, Long districtId) {
public AddPostRequest(Category category, String title, String subTitle, String description, String level, String time, String distance, String courseDetail, String transportation, Long districtId, GetGeometryResponse geometry) {
this.category = category;
this.title = title;
this.subTitle = subTitle;
Expand All @@ -53,5 +58,6 @@ public AddPostRequest(Category category, String title, String subTitle, String d
this.courseDetail = courseDetail;
this.transportation = transportation;
this.districtId = districtId;
this.geometry = geometry;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import org.springframework.util.Assert;

public record GetPostResponse(Long id, Category category, String title, String subTitle, String description, String level, String time,
String distance, String courseDetail, String transportation, String districtName, GetCoordinateResponse coordinate) {
String distance, String courseDetail, String transportation, String districtName, GetCoordinateResponse geometry) {

public GetPostResponse {
Assert.hasText(title, "제목은 필수입니다.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
import com.seoultech.sanEseo.post.domain.Post;
import com.seoultech.sanEseo.post_district.domain.PostDistrict;
import com.seoultech.sanEseo.post_district.application.port.PostDistrictPort;
import com.seoultech.sanEseo.public_api.Coordinate;
import com.seoultech.sanEseo.public_api.CoordinateService;
import com.seoultech.sanEseo.public_api.GetCoordinateResponse;
import com.seoultech.sanEseo.public_api.GetGeometryResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -22,6 +24,7 @@ public class PostService {
private final PostDistrictPort postDistrictPort;
private final CoordinateService coordinateService;


public PostService(PostPort postPort, DistrictPort districtPort, PostDistrictPort postDistrictPort, CoordinateService coordinateService) {
this.postPort = postPort;
this.districtPort = districtPort;
Expand All @@ -43,6 +46,9 @@ public Post addPost(AddPostRequest request) {
request.getLevel(), request.getTime(), request.getDistance(), request.getCourseDetail(),
request.getTransportation());

GetGeometryResponse geometry = request.getGeometry();
coordinateService.saveCoordinate(geometry, post);

postPort.save(post); // Post 저장

// 관련 District와 PostDistrict 관계 설정
Expand All @@ -60,19 +66,25 @@ public GetPostResponse getPost(Long postId) {
Post post = postPort.getPost(postId);
List<PostDistrict> postDistrictList = postDistrictPort.findByPostId(postId);
String postDistrictName = postDistrictList.get(0).getDistrict().getName();
GetCoordinateResponse coordinate = coordinateService.getCoordinateResponse(post);
GetCoordinateResponse geometry = coordinateService.getCoordinateResponse(post);

return new GetPostResponse(
post.getId(), post.getCategory(), post.getTitle(), post.getSubTitle(),
post.getDescription(), post.getLevel(), post.getTime(),
post.getDistance(),post.getCourseDetail(), post.getTransportation(), postDistrictName
,coordinate
, geometry
);
}

@Transactional
public void updatePost(Long postId, UpdatePostRequest request) {
Post post = postPort.getPost(postId);

// 좌표 정보 업데이트
Coordinate coordinate = coordinateService.findCoordinate(post);
coordinate.update(request.getGeometry().getName(), request.getGeometry().getType(), request.getGeometry());

// 게시글 정보 업데이트
post.update(
request.getCategory(), request.getTitle(), request.getSubTitle(),
request.getDescription(), request.getLevel(), request.getTime(),
Expand All @@ -96,7 +108,7 @@ public void deletePost(Long postId) {
postDistrictPort.deleteAll(relations);

postPort.deletePost(postId);

}


}
Loading