Skip to content

Commit

Permalink
API - v0.1.6
Browse files Browse the repository at this point in the history
API - v0.1.6
  • Loading branch information
wjdtkdgns authored Aug 28, 2023
2 parents bfc7a34 + c5f031b commit 98fcc0d
Show file tree
Hide file tree
Showing 15 changed files with 171 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import allchive.server.api.common.util.UrlUtil;
import allchive.server.api.config.security.SecurityUtil;
import allchive.server.core.annotation.UseCase;
import allchive.server.core.event.Event;
import allchive.server.core.event.events.s3.S3ImageDeleteEvent;
import allchive.server.domain.domains.archiving.adaptor.ArchivingAdaptor;
import allchive.server.domain.domains.archiving.domain.Archiving;
import allchive.server.domain.domains.archiving.service.ArchivingDomainService;
Expand Down Expand Up @@ -44,7 +46,7 @@ private void eliminateOldImage(Long archivingId, String newUrl) {
Archiving archiving = archivingAdaptor.findById(archivingId);
if (UrlUtil.validateS3Key(archiving.getImageUrl())
&& !archiving.getImageUrl().equals(UrlUtil.convertUrlToKey(newUrl))) {
s3DeleteObjectService.deleteS3Object(List.of(archiving.getImageUrl()));
Event.raise(S3ImageDeleteEvent.from(List.of(archiving.getImageUrl())));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ public class ContentController {

@Operation(summary = "컨텐츠를 생성합니다.")
@PostMapping()
public void createContent(@RequestBody CreateContentRequest createContentRequest) {
createContentUseCase.execute(createContentRequest);
public ContentTagResponse createContent(
@RequestBody CreateContentRequest createContentRequest) {
return createContentUseCase.execute(createContentRequest);
}

@Operation(summary = "컨텐츠 내용을 가져옵니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import allchive.server.api.config.security.SecurityUtil;
import allchive.server.api.content.model.dto.request.CreateContentRequest;
import allchive.server.api.content.model.dto.response.ContentTagResponse;
import allchive.server.api.content.model.mapper.ContentMapper;
import allchive.server.core.annotation.UseCase;
import allchive.server.domain.domains.archiving.service.ArchivingDomainService;
Expand Down Expand Up @@ -33,27 +34,30 @@ public class CreateContentUseCase {
private final ArchivingDomainService archivingDomainService;

@Transactional
public void execute(CreateContentRequest request) {
validateExecution(request);
public ContentTagResponse execute(CreateContentRequest request) {
Long userId = SecurityUtil.getCurrentUserId();
validateExecution(userId, request);
Content content = contentMapper.toEntity(request);
updateTagUsedAt(request.getTagIds());
createContentTagGroup(content, request.getTagIds());
List<ContentTagGroup> contentTagGroupList =
createContentTagGroup(content, request.getTagIds());
contentDomainService.save(content);
archivingDomainService.updateContentCnt(
request.getArchivingId(), request.getContentType(), PLUS_ONE);
return contentMapper.toContentTagResponse(content, contentTagGroupList, true, userId);
}

private void validateExecution(CreateContentRequest request) {
Long userId = SecurityUtil.getCurrentUserId();
private void validateExecution(Long userId, CreateContentRequest request) {
archivingValidator.verifyUser(userId, request.getArchivingId());
tagValidator.validateExistTagsAndUser(request.getTagIds(), userId);
}

private void createContentTagGroup(Content content, List<Long> tagIds) {
private List<ContentTagGroup> createContentTagGroup(Content content, List<Long> tagIds) {
List<Tag> tags = tagAdaptor.queryTagByTagIdIn(tagIds);
List<ContentTagGroup> contentTagGroupList =
contentMapper.toContentTagGroupEntityList(content, tags);
contentTagGroupDomainService.saveAll(contentTagGroupList);
return contentTagGroupList;
}

private void updateTagUsedAt(List<Long> tagIds) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import allchive.server.api.content.model.dto.request.UpdateContentRequest;
import allchive.server.api.content.model.mapper.ContentMapper;
import allchive.server.core.annotation.UseCase;
import allchive.server.core.event.Event;
import allchive.server.core.event.events.s3.S3ImageDeleteEvent;
import allchive.server.domain.domains.archiving.service.ArchivingDomainService;
import allchive.server.domain.domains.content.adaptor.ContentAdaptor;
import allchive.server.domain.domains.content.adaptor.TagAdaptor;
Expand Down Expand Up @@ -87,7 +89,7 @@ private void eliminateOldImage(Long contentId, String newUrl) {
Content content = contentAdaptor.findById(contentId);
if (UrlUtil.validateS3Key(content.getImageUrl())
&& !content.getImageUrl().equals(UrlUtil.convertUrlToKey(newUrl))) {
s3DeleteObjectService.deleteS3Object(List.of(content.getImageUrl()));
Event.raise(S3ImageDeleteEvent.from(List.of(content.getImageUrl())));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import allchive.server.api.config.security.SecurityUtil;
import allchive.server.api.recycle.model.dto.request.ClearDeletedObjectRequest;
import allchive.server.core.annotation.UseCase;
import allchive.server.core.event.Event;
import allchive.server.core.event.events.s3.S3ImageDeleteEvent;
import allchive.server.domain.domains.archiving.adaptor.ArchivingAdaptor;
import allchive.server.domain.domains.archiving.domain.Archiving;
import allchive.server.domain.domains.archiving.service.ArchivingDomainService;
Expand Down Expand Up @@ -73,7 +75,7 @@ private void deleteS3Object(List<Content> contents, List<Archiving> archivings)
.filter(url -> !url.isEmpty())
.filter(url -> !url.startsWith("http"))
.collect(Collectors.toList()));
s3DeleteObjectService.deleteS3Object(imageKeys);
Event.raise(S3ImageDeleteEvent.from(imageKeys));
}

private List<Long> getContentsId(List<Content> contents, ClearDeletedObjectRequest request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@


import allchive.server.core.annotation.UseCase;
import allchive.server.core.event.Event;
import allchive.server.core.event.events.s3.S3ImageDeleteEvent;
import allchive.server.domain.domains.archiving.adaptor.ArchivingAdaptor;
import allchive.server.domain.domains.archiving.domain.Archiving;
import allchive.server.domain.domains.archiving.service.ArchivingDomainService;
Expand Down Expand Up @@ -76,7 +78,7 @@ private void deleteS3Object(List<Content> contents, List<Archiving> archivings)
.filter(url -> !url.isEmpty())
.filter(url -> !url.startsWith("http"))
.collect(Collectors.toList()));
s3DeleteObjectService.deleteS3Object(imageKeys);
Event.raise(S3ImageDeleteEvent.from(imageKeys));
}

private List<Long> getArchivingIds(List<Recycle> recycles) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import allchive.server.api.config.security.SecurityUtil;
import allchive.server.api.user.model.dto.request.UpdateUserInfoRequest;
import allchive.server.core.annotation.UseCase;
import allchive.server.core.event.Event;
import allchive.server.core.event.events.s3.S3ImageDeleteEvent;
import allchive.server.domain.domains.user.adaptor.UserAdaptor;
import allchive.server.domain.domains.user.domain.User;
import allchive.server.domain.domains.user.service.UserDomainService;
Expand Down Expand Up @@ -43,7 +45,7 @@ private void eliminateOldImage(Long userId, String newUrl) {
User user = userAdaptor.findById(userId);
if (UrlUtil.validateS3Key(user.getProfileImgUrl())
&& !user.getProfileImgUrl().equals(UrlUtil.convertUrlToKey(newUrl))) {
s3DeleteObjectService.deleteS3Object(List.of(user.getProfileImgUrl()));
Event.raise(S3ImageDeleteEvent.from(List.of(user.getProfileImgUrl())));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package allchive.server.core.async;


import java.lang.reflect.Method;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... params) {
log.error("Exception message - " + throwable);
log.error("Method name - " + method.getName());
for (Object param : params) {
log.error("Parameter value - " + param);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package allchive.server.core.config;

import static allchive.server.core.consts.AllchiveConst.*;

import allchive.server.core.async.CustomAsyncExceptionHandler;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import lombok.RequiredArgsConstructor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@EnableAsync
@Configuration
@RequiredArgsConstructor
public class EnableAsyncConfig implements AsyncConfigurer {

private final CustomAsyncExceptionHandler customAsyncExceptionHandler;

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return customAsyncExceptionHandler;
}

@Bean(name = "s3ImageTaskExecutor")
public Executor s3ImageTaskExecutor() {
return createTaskExecutor("S3_IMAGE_TASK_EXECUTOR");
}

private Executor createTaskExecutor(String name) {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
taskExecutor.setQueueCapacity(QUEUE_CAPACITY);
taskExecutor.setThreadNamePrefix(name);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,8 @@ public class AllchiveConst {
public static final int PLUS_ONE = 1;
public static final int MINUS_ONE = -1;
public static final int ZERO = 0;

public static final int CORE_POOL_SIZE = 1;
public static final int MAX_POOL_SIZE = 30;
public static final int QUEUE_CAPACITY = 500;
}
18 changes: 18 additions & 0 deletions Core/src/main/java/allchive/server/core/event/Event.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package allchive.server.core.event;


import org.springframework.context.ApplicationEventPublisher;

public class Event {
private static ApplicationEventPublisher publisher;

static void setPublisher(ApplicationEventPublisher publisher) {
Event.publisher = publisher;
}

public static void raise(Object event) {
if (publisher != null) {
publisher.publishEvent(event);
}
}
}
18 changes: 18 additions & 0 deletions Core/src/main/java/allchive/server/core/event/EventConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package allchive.server.core.event;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EventConfig {
@Autowired private ApplicationEventPublisher applicationEventPublisher;

@Bean
public InitializingBean eventsInitializer() {
return () -> Event.setPublisher(applicationEventPublisher);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package allchive.server.core.event.events.s3;


import java.util.List;
import lombok.Builder;
import lombok.Getter;

@Getter
public class S3ImageDeleteEvent {
private final List<String> keys;

@Builder
private S3ImageDeleteEvent(List<String> keys) {
this.keys = keys;
}

public static S3ImageDeleteEvent from(List<String> keys) {
return S3ImageDeleteEvent.builder().keys(keys).build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public Slice<Archiving> querySliceArchivingByUserId(
.select(archiving)
.from(archiving)
.where(userIdEq(userId), categoryEq(category), deleteStatusFalse())
.orderBy(pinDesc(userId), scrapCntDesc(), createdAtDesc())
.orderBy(pinDesc(userId), createdAtDesc())
.offset(pageable.getOffset())
.limit(pageable.getPageSize() + PLUS_ONE)
.fetch();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@


import allchive.server.core.error.exception.S3ObjectNotFoundException;
import allchive.server.core.event.events.s3.S3ImageDeleteEvent;
import com.amazonaws.services.s3.AmazonS3;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Service
@RequiredArgsConstructor
Expand All @@ -16,12 +19,18 @@ public class S3DeleteObjectService {
@Value("${aws.s3.bucket}")
private String bucket;

public void deleteS3Object(List<String> keys) {
keys.forEach(
key -> {
validateExistObject(key);
amazonS3.deleteObject(bucket, key);
});
@Async(value = "s3ImageTaskExecutor")
@TransactionalEventListener(
value = S3ImageDeleteEvent.class,
phase = TransactionPhase.AFTER_COMMIT)
public void deleteS3Object(S3ImageDeleteEvent s3ImageDeleteEvent) {
s3ImageDeleteEvent
.getKeys()
.forEach(
key -> {
validateExistObject(key);
amazonS3.deleteObject(bucket, key);
});
}

private void validateExistObject(String key) {
Expand Down

0 comments on commit 98fcc0d

Please sign in to comment.