Skip to content

Commit

Permalink
[KAN-8] ArticleService 리팩토링 작업 (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
nohy6630 authored May 29, 2024
2 parents ec1e165 + f51af54 commit 00e6dac
Show file tree
Hide file tree
Showing 22 changed files with 352 additions and 499 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.numberone.backend.domain.article.service.ArticleService;
import com.numberone.backend.domain.comment.dto.request.CreateCommentRequest;
import com.numberone.backend.domain.comment.dto.response.CreateCommentResponse;
import com.numberone.backend.provider.security.SecurityContextProvider;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -43,8 +44,8 @@ public class ArticleController {

@PostMapping
public ResponseEntity<UploadArticleResponse> uploadArticle(@ModelAttribute @Valid UploadArticleRequest request) {
return ResponseEntity.created(URI.create("/api/articles"))
.body(articleService.uploadArticle(request));
Long userId = SecurityContextProvider.getAuthenticatedUserId();
return ResponseEntity.created(URI.create("/api/articles")).body(articleService.uploadArticle(request, userId));
}

@Operation(summary = "게시글을 삭제하는 API 입니다.", description = """
Expand All @@ -61,7 +62,8 @@ public ResponseEntity<DeleteArticleResponse> deleteArticle(@PathVariable("articl
""")
@GetMapping("{article-id}")
public ResponseEntity<GetArticleDetailResponse> getArticleDetails(@PathVariable("article-id") Long articleId) {
return ResponseEntity.ok(articleService.getArticleDetail(articleId));
Long userId = SecurityContextProvider.getAuthenticatedUserId();
return ResponseEntity.ok(articleService.getArticleDetail(articleId, userId));
}


Expand All @@ -84,12 +86,14 @@ public ResponseEntity<GetArticleDetailResponse> getArticleDetails(@PathVariable(
""")
@GetMapping
public ResponseEntity<Slice<GetArticleListResponse>> getArticlePages(
public ResponseEntity<Slice<GetArticleListResponse>> getArticleList(
Pageable pageable,
@ModelAttribute ArticleSearchParameterDto paramDto) {
return ResponseEntity.ok(articleService.getArticleListPaging(paramDto.toParameter(), pageable));
Long userId = SecurityContextProvider.getAuthenticatedUserId();
return ResponseEntity.ok(articleService.getArticleList(userId, paramDto.toParameter(), pageable));
}


@Operation(summary = "게시글에 댓글 작성하기", description = """
게시글에 댓글을 작성하는 API 입니다.
Expand Down Expand Up @@ -120,6 +124,4 @@ public ResponseEntity<ModifyArticleResponse> modifyArticle(
return ResponseEntity.ok(articleService.modifyArticle(articleId, request));
}

// todo: 게시글 신고 기능

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,23 @@

import com.numberone.backend.domain.article.entity.ArticleTag;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@ToString
@Builder
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class ModifyArticleRequest {

// 글 관련
@NotNull(message = "글 제목은 null 일 수 없습니다.")
private String title; // 제목

@NotNull(message = "내용은 null 일 수 없습니다.")
private String content; // 내용

@NotNull(message = """
게시글의 태그를 하나 선택해주세요.
LIFE(일상), FRAUD(사기), SAFETY(안전), REPORT(제보)
""")
private ArticleTag articleTag; // 게시글 태그

// 이미지 관련
private List<MultipartFile> imageList; // 이미지 리스트
private Long thumbNailImageIdx; // 썸네일 이미지의 순서 (0,1,2,...)

private Double longitude;
private Double latitude;

public record ModifyArticleRequest(
@NotNull(message = "글 제목은 null 일 수 없습니다.")
String title,
@NotNull(message = "내용은 null 일 수 없습니다.")
String content,
@NotNull(message = "게시글의 태그를 하나 선택해주세요. LIFE(일상), FRAUD(사기), SAFETY(안전), REPORT(제보)")
ArticleTag articleTag,
List<MultipartFile> imageList,
Long thumbNailImageIdx,
Double longitude,
Double latitude
) {
public boolean hasImage() {
return imageList != null && !imageList.isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,27 @@

import com.numberone.backend.domain.article.entity.ArticleTag;
import jakarta.validation.constraints.NotNull;
import lombok.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@ToString
@Builder
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class UploadArticleRequest {

// 글 관련
@NotNull(message = "글 제목은 null 일 수 없습니다.")
private String title; // 제목

@NotNull(message = "내용은 null 일 수 없습니다.")
private String content; // 내용

@NotNull(message = """
게시글의 태그를 하나 선택해주세요.
""")
private ArticleTag articleTag; // 게시글 태그

// 이미지 관련
private List<MultipartFile> imageList; // 이미지 리스트

private Double longitude;
private Double latitude;

@NotNull(message = "동 위치 정보 제공 동의는 null 일 수 없습니다.")
private boolean regionAgreementCheck; // 동 정보 제공 동의

public record UploadArticleRequest(
@NotNull(message = "글 제목은 null 일 수 없습니다.")
String title,
@NotNull(message = "내용은 null 일 수 없습니다.")
String content,
@NotNull(message = "게시글 태그는 null 일 수 없습니다.")
ArticleTag articleTag,
List<MultipartFile> imageList,
Double longitude,
Double latitude,
@NotNull(message = "위치 정보 제공 동의는 null 일 수 없습니다.")
Boolean regionAgreementCheck
) {
public boolean isValidPosition(){
return (longitude != null) && (latitude != null);
}
public boolean hasImage() {
return imageList != null && !imageList.isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,93 +3,69 @@
import com.fasterxml.jackson.annotation.JsonFormat;
import com.numberone.backend.domain.article.entity.Article;
import com.numberone.backend.domain.article.entity.ArticleTag;
import com.numberone.backend.domain.articleimage.entity.ArticleImage;
import com.numberone.backend.domain.member.entity.Member;
import lombok.*;
import lombok.Builder;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@ToString
@Builder
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class GetArticleDetailResponse {

// 게시글 관련
private Long articleId;
private Integer likeCount;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
private LocalDateTime createdAt;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
private LocalDateTime modifiedAt;
private String title;
private String content;
private boolean isLiked;
private ArticleTag articleTag;
private Long commentCount;

// 작성자 관련
private String ownerName;
private String ownerNickName;
private String address;
private String regionLv2;
private Long ownerMemberId;
private String ownerProfileImageUrl;

// 이미지 관련
private List<String> imageUrls;
private String thumbNailImageUrl;

public static GetArticleDetailResponse of(
Article article,
List<String> imageUrls,
String thumbNailImageUrl,
Member owner,
List<Long> memberLikedArticleList,
Long commentCount ) {

String address = "";

String articleAddress = article.getAddress();
if(!articleAddress.isEmpty()){
String[] elements = articleAddress.split(" ");
switch (elements.length){
case 3 -> address = elements[2];
case 2 -> address = elements[1];
case 1 -> address = elements[0];
default ->address = "";
}
} else {
address = "";
}


public record GetArticleDetailResponse(
Long articleId,
Integer likeCount,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
LocalDateTime createdAt,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
LocalDateTime modifiedAt,
String title,
String content,
Boolean isLiked,
ArticleTag articleTag,
Long commentCount,
String ownerName,
String ownerNickName,
String address,
String regionLv2,
Long ownerMemberId,
String ownerProfileImageUrl,
List<String> imageUrls,
String thumbNailImageUrl
) {
public static GetArticleDetailResponse of(Article article,
List<ArticleImage> images,
Member owner,
boolean isLiked,
Long commentCount) {
List<String> imageUrls = images.stream().map(ArticleImage::getImageUrl).toList();
return GetArticleDetailResponse.builder()
.articleId(article.getId())
.title(article.getTitle())
.content(article.getContent())
.likeCount(
Optional.ofNullable(
article.getLikeCount()
).orElse(0)
)
.likeCount(Optional.ofNullable(article.getLikeCount()).orElse(0))
.createdAt(article.getCreatedAt())
.modifiedAt(article.getModifiedAt())
.ownerMemberId(owner.getId())
.ownerName(owner.getRealName())
.ownerNickName(owner.getNickName())
.imageUrls(imageUrls)
.thumbNailImageUrl(thumbNailImageUrl)
.address(address)
.imageUrls(images.stream().map(ArticleImage::getImageUrl).toList())
.thumbNailImageUrl(imageUrls.isEmpty() ? "" : imageUrls.get(0))
.address(getAddress(article))
.ownerProfileImageUrl(owner.getProfileImageUrl())
.isLiked(memberLikedArticleList.contains(article.getId()))
.isLiked(isLiked)
.articleTag(article.getArticleTag())
.commentCount(commentCount)
.regionLv2(Optional.ofNullable(article.getLv2())
.orElse(""))
.regionLv2(Optional.ofNullable(article.getLv2()).orElse(""))
.build();
}

private static String getAddress(Article article) {
String address = article.getAddress();
if (!address.isEmpty()) {
String[] tokens = address.split(" ");
int length = tokens.length;
return length > 0 ? tokens[length - 1] : "";
}
return "";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,38 @@

import com.fasterxml.jackson.annotation.JsonFormat;
import com.numberone.backend.domain.article.entity.Article;
import lombok.*;
import com.numberone.backend.domain.articleimage.entity.ArticleImage;
import lombok.Builder;

import java.time.LocalDateTime;
import java.util.List;

@ToString
@Builder
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public class ModifyArticleResponse {

private Long articleId;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
private LocalDateTime createdAt;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
private LocalDateTime modifiedAt;

// 이미지 관련
private List<String> imageUrls;
private String thumbNailImageUrl;

// 작성자 주소
private String address;

public static ModifyArticleResponse of(Article article, List<String> imageUrls, String thumbNailImageUrl){
public record ModifyArticleResponse(
Long articleId,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
LocalDateTime createdAt,
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm", timezone = "Asia/Seoul")
LocalDateTime modifiedAt,
List<String> imageUrls,
String thumbNailImageUrl,
String address
) {
public static ModifyArticleResponse from(Article article) {
return ModifyArticleResponse.builder()
.articleId(article.getId())
.createdAt(article.getCreatedAt())
.modifiedAt(article.getModifiedAt())
.imageUrls(imageUrls)
.thumbNailImageUrl(thumbNailImageUrl)
.address(article.getAddress())
.build();
}

public static ModifyArticleResponse ofImages(Article article, List<ArticleImage> images) {
return ModifyArticleResponse.builder()
.articleId(article.getId())
.createdAt(article.getCreatedAt())
.imageUrls(images.stream().map(ArticleImage::getImageUrl).toList())
.thumbNailImageUrl(images.isEmpty() ? "" : images.get(0).getImageUrl())
.address(article.getAddress())
.build();
}
}
Loading

0 comments on commit 00e6dac

Please sign in to comment.