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

feat: 카테고리 API 구현 #33

Merged
merged 4 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.potatocake.everymoment.controller;

import com.potatocake.everymoment.dto.SuccessResponse;
import com.potatocake.everymoment.dto.request.CategoryCreateRequest;
import com.potatocake.everymoment.dto.response.CategoryResponse;
import com.potatocake.everymoment.security.MemberDetails;
import com.potatocake.everymoment.service.CategoryService;
import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
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;

@RequiredArgsConstructor
@RequestMapping("/api/categories")
@RestController
public class CategoryController {

private final CategoryService categoryService;

@GetMapping
public ResponseEntity<SuccessResponse<CategoryResponse>> getCategories(
@AuthenticationPrincipal MemberDetails memberDetails) {
List<CategoryResponse> categories = categoryService.getCategories(memberDetails.getId());

return ResponseEntity.ok()
.body(SuccessResponse.ok(categories));
}

@PostMapping
public ResponseEntity<SuccessResponse> addCategory(@RequestBody @Valid CategoryCreateRequest request,
@AuthenticationPrincipal MemberDetails memberDetails) {
categoryService.addCategory(memberDetails.getId(), request);

return ResponseEntity.ok()
.body(SuccessResponse.ok());
}

@PatchMapping("/{categoryId}")
public ResponseEntity<SuccessResponse> updateCategory(@PathVariable Long categoryId,
@RequestBody @Valid CategoryCreateRequest request,
@AuthenticationPrincipal MemberDetails memberDetails) {
categoryService.updateCategory(categoryId, memberDetails.getId(), request);

return ResponseEntity.ok()
.body(SuccessResponse.ok());
}

@DeleteMapping("/{categoryId}")
public ResponseEntity<SuccessResponse> deleteCategory(@PathVariable Long categoryId,
@AuthenticationPrincipal MemberDetails memberDetails) {
categoryService.deleteCategory(categoryId, memberDetails.getId());

return ResponseEntity.ok()
.body(SuccessResponse.ok());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.potatocake.everymoment.dto.request;

import com.potatocake.everymoment.entity.Category;
import com.potatocake.everymoment.entity.Member;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import org.hibernate.validator.constraints.Length;

@Getter
public class CategoryCreateRequest {

@Length(max = 50)
@NotEmpty
private String categoryName;

public Category toEntity(Member member) {
return Category.builder()
.member(member)
.categoryName(categoryName)
.build();
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.potatocake.everymoment.dto.response;

import com.potatocake.everymoment.entity.Category;
import lombok.Builder;
import lombok.Getter;

Expand All @@ -8,4 +9,12 @@
public class CategoryResponse {
private long id;
private String categoryName;
}

public static CategoryResponse from(Category category) {
return CategoryResponse.builder()
.id(category.getId())
.categoryName(category.getCategoryName())
.build();
}

}
21 changes: 21 additions & 0 deletions src/main/java/com/potatocake/everymoment/entity/Category.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package com.potatocake.everymoment.entity;

import com.potatocake.everymoment.exception.ErrorCode;
import com.potatocake.everymoment.exception.GlobalException;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.ForeignKey;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
Expand All @@ -23,4 +29,19 @@ public class Category {

@Column(length = 50, nullable = false)
private String categoryName;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(name = "fk_member_id"), nullable = false)
private Member member;

public void checkOwner(Long memberId) {
if (!member.getId().equals(memberId)) {
throw new GlobalException(ErrorCode.CATEGORY_NOT_OWNER);
}
}

public void update(String categoryName) {
this.categoryName = categoryName;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ public enum ErrorCode {

INFO_REQUIRED("정보를 입력해 주세요.", BAD_REQUEST),

METHOD_NOT_ALLOWED("지원하지 않는 HTTP 메소드입니다.", HttpStatus.METHOD_NOT_ALLOWED);
METHOD_NOT_ALLOWED("지원하지 않는 HTTP 메소드입니다.", HttpStatus.METHOD_NOT_ALLOWED),

/* CategoryService */
CATEGORY_NOT_OWNER("본인의 카테고리만 수정할 수 있습니다.", HttpStatus.FORBIDDEN);

private final String message;
private final HttpStatus status;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,26 @@

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import java.util.HashMap;
import java.util.Map;
import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
@JsonInclude(Include.NON_NULL)
public class ErrorResponse {

private int code;
private String message;
private Map<String, String> validation;

@Builder
public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
this.validation = new HashMap<>();
}

public void addValidation(String fieldName, String errorMessage) {
this.validation.put(fieldName, errorMessage);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.potatocake.everymoment.repository;

import com.potatocake.everymoment.entity.Category;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CategoryRepository extends JpaRepository<Category, Long> {

List<Category> findByMemberId(Long memberId);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.potatocake.everymoment.service;

import com.potatocake.everymoment.dto.request.CategoryCreateRequest;
import com.potatocake.everymoment.dto.response.CategoryResponse;
import com.potatocake.everymoment.entity.Category;
import com.potatocake.everymoment.entity.Member;
import com.potatocake.everymoment.exception.ErrorCode;
import com.potatocake.everymoment.exception.GlobalException;
import com.potatocake.everymoment.repository.CategoryRepository;
import com.potatocake.everymoment.repository.MemberRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Transactional
@Service
public class CategoryService {

private final CategoryRepository categoryRepository;
private final MemberRepository memberRepository;

public void addCategory(Long memberId, CategoryCreateRequest request) {
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GlobalException(ErrorCode.MEMBER_NOT_FOUND));

categoryRepository.save(request.toEntity(member));
}

public List<CategoryResponse> getCategories(Long memberId) {
return categoryRepository.findByMemberId(memberId).stream()
.map(CategoryResponse::from)
.toList();
}

public void updateCategory(Long categoryId, Long memberId, CategoryCreateRequest request) {
Category category = categoryRepository.findById(categoryId)
.orElseThrow(() -> new GlobalException(ErrorCode.CATEGORY_NOT_FOUND));

category.checkOwner(memberId);

category.update(request.getCategoryName());
}

public void deleteCategory(Long categoryId, Long memberId) {
Category category = categoryRepository.findById(categoryId)
.orElseThrow(() -> new GlobalException(ErrorCode.CATEGORY_NOT_FOUND));

category.checkOwner(memberId);

categoryRepository.delete(category);
}

}
Loading