Skip to content

Commit

Permalink
[Feat] 나의 서랍 목록 조회 API (#124)
Browse files Browse the repository at this point in the history
* [Feat] 나의 서랍 목록 조회 API

* [Feat] 인사이트 등록 시 서랍 주인 확인

* [Feat] 나의 서랍 조회 API 문서화 테스트

* [Fix] @transactional 추가

* [Fix] ERR444 코드 수정
  • Loading branch information
heoboseong7 authored Oct 9, 2022
1 parent 3034964 commit 3067188
Show file tree
Hide file tree
Showing 12 changed files with 126 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
import ccc.keeweapi.dto.ApiResponse;
import ccc.keeweapi.dto.insight.DrawerCreateRequest;
import ccc.keeweapi.dto.insight.DrawerCreateResponse;
import ccc.keeweapi.dto.insight.DrawerResponse;
import ccc.keeweapi.service.insight.DrawerApiService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/v1/drawer")
Expand All @@ -23,4 +22,9 @@ public class DrawerController {
public ApiResponse<DrawerCreateResponse> create(@RequestBody @Valid DrawerCreateRequest request) {
return ApiResponse.ok(drawerApiService.create(request));
}

@GetMapping
public ApiResponse<List<DrawerResponse>> getMyDrawers() {
return ApiResponse.ok(drawerApiService.getMyDrawers());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ public CommentCreateResponse toCommentCreateResponse(Comment comment) {
return CommentCreateResponse.of(comment.getId());
}

public DrawerResponse toDrawerResponse(Drawer drawer) {
return DrawerResponse.of(drawer.getId(), drawer.getName());
}

public InsightAuthorAreaResponse toInsightAuthorAreaResponse(Insight insight) {
User writer = insight.getWriter();
return InsightAuthorAreaResponse.of(insight.getId(), writer.getNickname(), "title", writer.getInterests(), "www.api-keewe.com/images" , isAuthor(insight), insight.getCreatedAt().toString());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ccc.keeweapi.dto.insight;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DrawerResponse {

private Long id;
private String name;

public static DrawerResponse of(Long id, String name) {
DrawerResponse response = new DrawerResponse();
response.id = id;
response.name = name;

return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public ChallengeParticipationResponse participate(ChallengeParticipateRequest re
return challengeAssembler.toChallengeParticipationResponse(participation);
}

@Transactional(readOnly = true)
public ParticipationCheckResponse checkParticipation() {
boolean participation = challengeDomainService.checkParticipation(SecurityUtil.getUserId());
return challengeAssembler.toParticipationCheckResponse(participation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@
import ccc.keeweapi.dto.insight.DrawerCreateRequest;
import ccc.keeweapi.dto.insight.DrawerCreateResponse;
import ccc.keeweapi.component.InsightAssembler;
import ccc.keeweapi.dto.insight.DrawerResponse;
import ccc.keeweapi.utils.SecurityUtil;
import ccc.keewedomain.persistence.domain.insight.Drawer;
import ccc.keewedomain.service.insight.DrawerDomainService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand All @@ -16,8 +22,18 @@ public class DrawerApiService {

private final InsightAssembler insightAssembler;

@Transactional
public DrawerCreateResponse create(DrawerCreateRequest request) {
Drawer drawer = drawerDomainService.create(insightAssembler.toDrawerCreateDto(request));
return insightAssembler.toDrawerCreateResponse(drawer);
}

@Transactional(readOnly = true)
public List<DrawerResponse> getMyDrawers() {
Long userId = SecurityUtil.getUserId();

return drawerDomainService.findAllByUserId(userId).stream()
.map(insightAssembler::toDrawerResponse)
.collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class InsightApiService {
private final InsightDomainService insightDomainService;
private final InsightAssembler insightAssembler;

@Transactional
public InsightCreateResponse create(InsightCreateRequest request) {
Insight insight = insightDomainService.create(insightAssembler.toInsightCreateDto(request));
return insightAssembler.toInsightCreateResponse(insight);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import ccc.keeweapi.document.utils.ApiDocumentationTest;
import ccc.keeweapi.dto.insight.DrawerCreateResponse;
import ccc.keeweapi.dto.insight.DrawerResponse;
import ccc.keeweapi.service.insight.DrawerApiService;
import com.epages.restdocs.apispec.ResourceSnippetParameters;
import org.json.JSONObject;
Expand All @@ -15,10 +16,13 @@
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.test.web.servlet.ResultActions;

import java.util.List;

import static com.epages.restdocs.apispec.ResourceDocumentation.headerWithName;
import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
Expand All @@ -38,7 +42,7 @@ void setup(RestDocumentationContextProvider provider) {

@Test
@DisplayName("서랍 등록 API")
void create_insight_test() throws Exception {
void create_drawer_test() throws Exception {
String drawerName = "개발";

JSONObject drawerCreateRequest = new JSONObject();
Expand Down Expand Up @@ -69,4 +73,36 @@ void create_insight_test() throws Exception {
.build()
)));
}

@Test
@DisplayName("나의 서랍 조회 API")
void get_my_drawers_test() throws Exception {
List<DrawerResponse> responses = List.of(
DrawerResponse.of(1L, "개발"),
DrawerResponse.of(2L, "공부"),
DrawerResponse.of(3L, "디자인")
);

when(drawerApiService.getMyDrawers()).thenReturn(responses);

ResultActions resultActions = mockMvc.perform(get("/api/v1/drawer")
.header(HttpHeaders.AUTHORIZATION, "Bearer " + JWT)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());

resultActions.andDo(restDocs.document(resource(
ResourceSnippetParameters.builder()
.description("나의 서랍 조회 API 입니다.")
.summary("나의 서랍 조회 API")
.requestHeaders(
headerWithName("Authorization").description("유저의 JWT"))
.responseFields(
fieldWithPath("message").description("요청 결과 메세지"),
fieldWithPath("code").description("결과 코드"),
fieldWithPath("data.[].id").description("서랍의 ID"),
fieldWithPath("data.[].name").description("서랍의 이름"))
.tag("Insight")
.build()
)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public enum KeeweRtnConsts {
ERR440(KeeweRtnGrp.Validation, 440, "서랍을 찾을 수 없어요"),
ERR441(KeeweRtnGrp.Validation, 441, "이미 등록된 서랍 이름이에요"),
ERR442(KeeweRtnGrp.Validation, 442, "댓글을 찾을 수 없어요"),
ERR444(KeeweRtnGrp.Validation, 444, "서랍의 주인이 아니에요."),
ERR443(KeeweRtnGrp.Validation, 443, "답글은 부모 댓글이 될 수 없어요."),
ERR445(KeeweRtnGrp.Validation, 445, "인사이트를 찾을 수 없어요."),

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ccc.keewedomain.persistence.domain.insight;

import ccc.keewecore.consts.KeeweRtnConsts;
import ccc.keewecore.exception.KeeweException;
import ccc.keewedomain.persistence.domain.common.BaseTimeEntity;
import ccc.keewedomain.persistence.domain.user.User;
import lombok.AccessLevel;
Expand Down Expand Up @@ -43,4 +45,10 @@ public static Drawer of(User user, String name) {

return drawer;
}

public void validateOwner(User user) {
if (this.user != user) {
throw new KeeweException(KeeweRtnConsts.ERR444);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package ccc.keewedomain.persistence.repository.insight;

import ccc.keewecore.consts.KeeweRtnConsts;
import ccc.keewecore.exception.KeeweException;
import ccc.keewedomain.persistence.domain.insight.Drawer;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;

public interface DrawerRepository extends JpaRepository<Drawer, Long>, DrawerQueryRepository {
Optional<Drawer> findByIdAndAndDeletedFalse(Long id);
Optional<Drawer> findByIdAndDeletedFalse(Long id);
List<Drawer> findAllByUserIdAndDeletedFalse(Long userId);

default Drawer findByIdOrElseThrow(Long id) {
return findByIdAndDeletedFalse(id).orElseThrow(() -> new KeeweException(KeeweRtnConsts.ERR442));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
Expand All @@ -27,13 +29,28 @@ public Drawer create(DrawerCreateDto dto) {
return drawerRepository.save(drawer);
}

public List<Drawer> findAllByUserId(Long userId) {
return drawerRepository.findAllByUserIdAndDeletedFalse(userId);
}

public Optional<Drawer> findById(Long id) {
return drawerRepository.findByIdAndAndDeletedFalse(id);
return drawerRepository.findByIdAndDeletedFalse(id);
}

private void validateNameDuplication(Long userId, String name) {
if(drawerRepository.existsByUserIdAndName(userId, name)) {
throw new KeeweException(KeeweRtnConsts.ERR441);
}
}

public Drawer getDrawerIfOwner(Long drawerId, User user) {
if (Objects.isNull(drawerId)) {
return null;
}

Drawer drawer = drawerRepository.findByIdOrElseThrow(drawerId);
drawer.validateOwner(user);

return drawer;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public class InsightDomainService {
//TODO 참가한 챌린지에 기록하기
public Insight create(InsightCreateDto dto) {
User writer = userDomainService.getUserByIdOrElseThrow(dto.getWriterId());
Drawer drawer = drawerDomainService.findById(dto.getDrawerId()).orElse(null);
Drawer drawer = drawerDomainService.getDrawerIfOwner(dto.getDrawerId(), writer);
ChallengeParticipation participation = challengeDomainService.findCurrentChallengeParticipation(dto.getWriterId())
.orElse(null);

Expand Down Expand Up @@ -109,4 +109,5 @@ private Long getViewCount(Long insightId) {
public Insight getById(Long id) {
return insightRepository.findById(id).orElseThrow(() -> new KeeweException(KeeweRtnConsts.ERR445));
}

}

0 comments on commit 3067188

Please sign in to comment.