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

경북대 BE_김동현_1주차 과제(2단계) #169

Open
wants to merge 24 commits into
base: donghyuun
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
902b824
chore: build setting modification
donghyuun Jun 26, 2024
4e8d336
docs: post README.md
donghyuun Jun 26, 2024
b8a1e9b
feat: create Product class
donghyuun Jun 26, 2024
1bb950d
feat: create Product DTO
donghyuun Jun 26, 2024
ddd17ee
refactor: Product
donghyuun Jun 26, 2024
5cdd9db
feat: add product
donghyuun Jun 26, 2024
9e860bf
feat: get product(s)
donghyuun Jun 26, 2024
d6fcb53
refactor: 상품의 id 정적 변수 -> 지역 변수 사용으로 변경
donghyuun Jun 26, 2024
5e3b595
feat: modify product
donghyuun Jun 26, 2024
22320ce
feat: delete product
donghyuun Jun 26, 2024
b260e4a
refactor: 모든 요청 방식 form-data -> raw-json 변경
donghyuun Jun 26, 2024
c937c17
refactor: controller -> controller + service
donghyuun Jun 26, 2024
ceb052a
feat: post, get 테스트코드 작성
donghyuun Jun 26, 2024
29d8beb
fix: @PathVariable 에 경로 변수 이름 명시
donghyuun Jun 26, 2024
7d6874f
feat: update, delete 테스트코드 작성
donghyuun Jun 26, 2024
5a6d0d3
fix: javadoc 의 설명 부분 한칸 띄움
donghyuun Jun 26, 2024
35718a5
chore: java 버전 변경 17 -> 21
donghyuun Jun 26, 2024
93d2b81
fix: API 수정 "/products" -> "/api/products"
donghyuun Jun 26, 2024
43d6adc
docs(README): add step2 README
donghyuun Jun 28, 2024
e104fac
feat: 상품 조회 기능(홈 페이지의 일부 기능)
donghyuun Jun 28, 2024
b99a57c
refactor: controller 내 상품 저장소 -> Repository 클래스 생성
donghyuun Jun 28, 2024
19f0229
feat: 상품 추가 기능
donghyuun Jun 28, 2024
0eafb22
feat: 상품 삭제, 수정 기능
donghyuun Jun 28, 2024
60171d0
docs(JavaDoc): javadoc 수정
donghyuun Jun 28, 2024
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
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
# spring-gift-product
# spring-gift-product

## 기능 목록
- 상품 추가 기능
- 상품 조회 기능
- 상품 수정 기능
- 상품 삭제 기능
- 상품 테스트 코드 작성
- 리팩토링
33 changes: 33 additions & 0 deletions src/main/java/gift/Controller/BasicController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package gift.Controller;

import gift.Service.ProductService;
import gift.model.Product;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/api")
public class BasicController {

private final ProductService productService;
@Autowired
public BasicController(ProductService productService) {
this.productService = productService;
}
@GetMapping
String homePage(Model model) {
// 현재 상품 목록 조회
Map<Long, Product> products = productService.getProducts();
for (Product value : products.values()) {
System.out.println("value = " + value);
}
System.out.println("products.size() = " + products.size());
model.addAttribute("products", products);
return "index";
}
}
126 changes: 126 additions & 0 deletions src/main/java/gift/Controller/ProductController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package gift.Controller;

import gift.Repository.ProductRepository;
import gift.Service.ProductService;
import gift.dto.ProductDTO;
import gift.model.Product;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping(value = "/api/products")
public class ProductController {


private final ProductService productService;
private final Map<Long, Product> products;

@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
this.products = ProductRepository.products;
}

/**
* 상품 추가
*
* @param productDTO git * @return 추가 성공 시 추가된 상품 정보, 실패 시 실패 메시지
*/
@PostMapping
@ResponseBody
public String postProduct(@ModelAttribute ProductDTO productDTO) {
String query = productService.postProduct(productDTO);
return query;
}

/**
* 상품 목록 전체 조회
*
* @return products (상품 목록)
*/
@GetMapping
public Map<Long, Product> getProducts() {
return productService.getProducts();
}

/**
* 특정 ID 값의 상품 조회
*
* @param id
* @return product (해당 ID 를 가진 상품)
*/
@GetMapping("/{id}")
public ResponseEntity<Object> getProduct(@PathVariable("id") Long id) {
return productService.getProduct(id);
}

/**
* 상품 내용 수정
*
* @param id
* @param productDTO
* @return product (수정된 상품 정보)
*/
@PutMapping("/{id}")
@ResponseBody
public String updateProduct(@PathVariable("id") Long id,
@RequestBody ProductDTO productDTO) {
String message = productService.updateProduct(id, productDTO);
return message;
}

/**
* 모든 상품 삭제
*
* @return 삭제 완료 메시지
*/
@DeleteMapping("/all")
public ResponseEntity<Object> deleteAllProducts() {
return productService.deleteAllProducts();
}

/**
* 해당 ID 리스트에 속한 상품 삭제
* @param productIds
* @return
*/
@DeleteMapping
@ResponseBody
public String deleteSelectedProducts(@RequestBody List<Long> productIds) {
String message = productService.deleteProductsByIds(productIds);
return message;
}

/**
* 해당 ID 를 가진 상품 삭제
*
* @param id
* @return product (삭제된 상품 정보)
*/
@DeleteMapping("/{id}")
@ResponseBody
public String deleteProduct(@PathVariable("id") Long id) {
return productService.deleteProduct(id);
}


}
24 changes: 24 additions & 0 deletions src/main/java/gift/Repository/ProductRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package gift.Repository;

import gift.Service.ProductService;
import gift.model.Product;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;

@Repository
public class ProductRepository {

// 상품 저장소
public static final Map<Long, Product> products = new HashMap<>();

public ProductRepository() {
Product product1 = new Product("아이스 아메리카노 T", 5500, "testImageUrl.com");
Product product2 = new Product("아이스 카푸치노 M", 5200, "testImageUrl.com");
Product product3 = new Product("핫 초코 프라푸치노 M", 6000, "testImageUrl.com");

products.put(product1.getId(), product1);
products.put(product2.getId(), product2);
products.put(product3.getId(), product3);
}
}
159 changes: 159 additions & 0 deletions src/main/java/gift/Service/ProductService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package gift.Service;

import gift.Repository.ProductRepository;
import gift.dto.ProductDTO;
import gift.model.Product;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

@Service
public class ProductService {

private final Map<Long, Product> products;

@Autowired
public ProductService(ProductRepository productRepository) {
this.products = productRepository.products;
}

/**
* 상품 추가
*
* @param productDTO
* @return 추가 성공 시 추가된 상품 정보, 실패 시 실패 메시지
*/
public String postProduct(ProductDTO productDTO) {
Product product = new Product(
productDTO.getName(),
productDTO.getPrice(),
productDTO.getImageUrl()
);
if (!existProduct(productDTO.getName())) {
products.put(product.getId(), product);
Product.increase();
return "상품이 성공적으로 추가되었습니다.";
}
return "해당 이름의 상품이 이미 존재합니다.";
}

/**
* 상품 목록 전체 조회
*
* @return products (상품 목록)
*/
public Map<Long, Product> getProducts() {
return products;
}

/**
* 특정 ID 값의 상품 조회
*
* @param id
* @return product (해당 ID 를 가진 상품)
*/
public ResponseEntity<Object> getProduct(Long id) {
Product product = products.get(id);
if (product == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("해당 ID의 상품이 존재하지 않습니다.");
}
return ResponseEntity.ok(product);
}

/**
* 상품 내용 수정
*
* @param id
* @param productDTO
* @return product (수정된 상품 정보)
*/
public String updateProduct(Long id, ProductDTO productDTO) {
Product product = products.get(id);
if (product == null) {
return "해당 ID의 상품이 존재하지 않습니다.";
}
if (existSameName(id, productDTO.getName())) {
return "수정할 이름을 가진 상품이 이미 존재합니다. 다른 이름을 입력하세요.";
}
product.setName(productDTO.getName());
product.setPrice(productDTO.getPrice());
product.setImageUrl(productDTO.getImageUrl());
products.put(product.getId(), product);

return "상품이 수정되었습니다.";
}

/**
* 모든 상품 삭제
*
* @return 삭제 완료 메시지
*/
public ResponseEntity<Object> deleteAllProducts() {
products.clear();
return ResponseEntity.ok("모든 상품을 삭제했습니다.");
}

/**
* 해당 ID 를 가진 상품 삭제
*
* @param id
* @return product (삭제된 상품 정보)
*/
public String deleteProduct(Long id) {
if (products.get(id) == null) {
return "해당 ID의 상품이 존재하지 않습니다";
}
products.remove(id);
return "상품이 삭제되었습니다.";
}

/**
* @param name
* @return 해당 이름을 가진 product 가 상품 목록에 존재하면 true, 그렇지 않으면 false
*/
public boolean existProduct(String name) {
for (Product p : products.values()) {
if (Objects.equals(name, p.getName())) {
return true;
}
}
return false;
}

/**
* 상품 이름 수정 시, 다른 상품들 중 해당 이름을 가진 상품이 있는지 확인
*
* @param id, name
* @return 상품 동일한 이름을 가진 product 가 이미 상품 목록에 존재하면 false, 그렇지 않으면 true
*/
public boolean existSameName(Long id, String name) {
for (Product p : products.values()) {
if (Objects.equals(name, p.getName()) && p.getId() != id) {
return true;
}
}
return false;
}

/**
* 해당 ID 리스트에 속한 상품들 삭제
* @param productIds
* @return 성공 여부 메시지
*/
public String deleteProductsByIds(List<Long> productIds) {
for (Long productId : productIds) {
products.remove(productId);
}
return "상품들이 성공적으로 제거되었습니다.";
}
}
Loading