Skip to content

Commit

Permalink
[FIX] 대상, 일시, 이미지 null 허용하도록 변경 및 좋아요수, 조회수, 저장 수 0으로 초기화 #25
Browse files Browse the repository at this point in the history
  • Loading branch information
eeddiinn committed Jul 13, 2024
1 parent 2009c5d commit ae7e7f0
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 45 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

implementation 'org.springframework.boot:spring-boot-starter-validation' // 유효성 검사 위해
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,5 @@ public class NoticeCreateRequest {
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private LocalDateTime endTime;

private List<MultipartFile> studentCardImages;

private List<MultipartFile> imageList;
}
5 changes: 5 additions & 0 deletions src/main/java/sopt/univoice/domain/notice/entity/Notice.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,12 @@ public class Notice extends BaseTimeEntity {
private Long noticeLike = 0L;

private Long viewCount = 0L;

private Long noticeSave = 0L;

private String target;


private LocalDateTime startTime;
private LocalDateTime endTime;

Expand Down Expand Up @@ -71,6 +75,7 @@ public Notice(String title, String content, String target, LocalDateTime startTi
this.member = member;
this.noticeLike = 0L;
this.viewCount = 0L;
this.noticeSave = 0L;
this.contentSummary = contentSummary;
this.category = category;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,16 @@ public class NoticeService {
private final PrincipalHandler principalHandler;
private final S3Service s3Service;
private final OpenAiService openAiService;
private final NoticeViewRepository noticeViewRepository;
private final NoticeLikeRepository noticeLikeRepository;
private final SaveNoticeRepository saveNoticeRepository;
private final NoticeViewRepository noticeViewRepository;

@Transactional
public void createPost(NoticeCreateRequest noticeCreateRequest) {
Long memberId = principalHandler.getUserIdFromPrincipal();
System.out.println("Authenticated Member ID: " + memberId);
Member member = authRepository.findById(memberId)
.orElseThrow(() -> new RuntimeException("회원이 존재하지 않습니다."));
.orElseThrow(() -> new RuntimeException("회원이 존재하지 않습니다."));
System.out.println("Member Role: " + member.getAffiliation().getRole());

String summarizedContent = null;
Expand All @@ -60,27 +60,36 @@ public void createPost(NoticeCreateRequest noticeCreateRequest) {

// Notice 엔티티 생성 및 저장
Notice notice = Notice.builder()
.title(noticeCreateRequest.getTitle())
.content(noticeCreateRequest.getContent())
.target(noticeCreateRequest.getTarget())
.startTime(noticeCreateRequest.getStartTime())
.endTime(noticeCreateRequest.getEndTime())
.member(member)
.contentSummary(summarizedContent)
.category("공지사항") // category 값을 '공지사항'으로 설정
.build();
.title(noticeCreateRequest.getTitle())
.content(noticeCreateRequest.getContent())
.target(noticeCreateRequest.getTarget() != null ? noticeCreateRequest.getTarget() : "")
.startTime(noticeCreateRequest.getStartTime() != null ? noticeCreateRequest.getStartTime() : null)
.endTime(noticeCreateRequest.getEndTime() != null ? noticeCreateRequest.getEndTime() : null)
.member(member)
.contentSummary(summarizedContent)
.category("공지사항") // category 값을 '공지사항'으로 설정
.build();
noticeRepository.save(notice);
System.out.println("Notice saved successfully with ID: " + notice.getId());

// NoticeImage 엔티티 생성 및 저장
for (MultipartFile file : noticeCreateRequest.getStudentCardImages()) {
String fileName = storeFile(file); // 파일 저장 로직 필요
NoticeImage noticeImage = NoticeImage.builder()
.notice(notice)
.noticeImage(fileName)
.build();
noticeImageRepository.save(noticeImage);
System.out.println("NoticeImage saved successfully with file name: " + fileName);
List<MultipartFile> files = noticeCreateRequest.getImageList();

if (files != null && !files.isEmpty()) {
for (MultipartFile file : files) {
try {
String fileUrl = storeFile(file); // 파일 저장 로직 필요
NoticeImage noticeImage = NoticeImage.builder()
.notice(notice)
.noticeImage(fileUrl)
.build();
noticeImageRepository.save(noticeImage);
System.out.println("NoticeImage saved successfully with file URL: " + fileUrl);
} catch (Exception e) {
System.err.println("Error saving NoticeImage: " + e.getMessage());
e.printStackTrace();
}
}
}

// NoticeView 엔티티 생성 및 저장
Expand All @@ -89,24 +98,24 @@ public void createPost(NoticeCreateRequest noticeCreateRequest) {

for (Member universityMember : universityMembers) {
NoticeView noticeView = NoticeView.builder()
.notice(notice)
.member(universityMember)
.readAt(false)
.build();
.notice(notice)
.member(universityMember)
.readAt(false)
.build();
noticeViewRepository.save(noticeView);
}

}

private String storeFile(MultipartFile file) {
try {
return s3Service.uploadImage("notice-images/", file);
String fileUrl = s3Service.uploadImage("notice-images/", file);
return fileUrl;
} catch (IOException e) {
System.err.println("File upload failed: " + e.getMessage());
throw new RuntimeException("파일 업로드에 실패했습니다.", e);
}
}


@Transactional
public void likeNotice(Long noticeId) {
Long memberId = principalHandler.getUserIdFromPrincipal();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package sopt.univoice.infra.common.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class ValidationExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
}
}

34 changes: 17 additions & 17 deletions src/main/java/sopt/univoice/infra/external/S3Service.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,17 @@ public class S3Service {

private final String bucketName;
private final AwsConfig awsConfig;
private final String region;
private static final List<String> IMAGE_EXTENSIONS = Arrays.asList("image/jpeg", "image/png", "image/jpg", "image/webp");


public S3Service(@Value("${aws-property.s3-bucket-name}") final String bucketName, AwsConfig awsConfig) {
public S3Service(@Value("${aws-property.s3-bucket-name}") final String bucketName,
AwsConfig awsConfig,
@Value("${aws-property.aws-region}") final String region) {
this.bucketName = bucketName;
this.awsConfig = awsConfig;
this.region = region;
}


public String uploadImage(String directoryPath, MultipartFile image) throws IOException {
final String key = directoryPath + generateImageFileName();
final S3Client s3Client = awsConfig.getS3Client();
Expand All @@ -37,33 +39,33 @@ public String uploadImage(String directoryPath, MultipartFile image) throws IOEx
validateFileSize(image);

PutObjectRequest request = PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
.contentType(image.getContentType())
.contentDisposition("inline")
.build();
.bucket(bucketName)
.key(key)
.contentType(image.getContentType())
.contentDisposition("inline")
.build();

RequestBody requestBody = RequestBody.fromBytes(image.getBytes());
s3Client.putObject(request, requestBody);
return key;

// Return the URL of the uploaded image
return String.format("https://%s.s3.%s.amazonaws.com/%s", bucketName, region, key);
}

public void deleteImage(String key) throws IOException {
final S3Client s3Client = awsConfig.getS3Client();

s3Client.deleteObject((DeleteObjectRequest.Builder builder) ->
builder.bucket(bucketName)
.key(key)
.build()
builder.bucket(bucketName)
.key(key)
.build()
);
}


private String generateImageFileName() {
return UUID.randomUUID() + ".jpg";
}


private void validateExtension(MultipartFile image) {
String contentType = image.getContentType();
if (!IMAGE_EXTENSIONS.contains(contentType)) {
Expand All @@ -78,6 +80,4 @@ private void validateFileSize(MultipartFile image) {
throw new RuntimeException("이미지 사이즈는 5MB를 넘을 수 없습니다.");
}
}

}

}

0 comments on commit ae7e7f0

Please sign in to comment.