Skip to content

Commit

Permalink
Merge pull request #11 from zenibakoLee/main
Browse files Browse the repository at this point in the history
백엔드 생존코스 7기 이해준
  • Loading branch information
bbhye1 authored Mar 4, 2024
2 parents e1ed3c9 + a626d8d commit 18a6692
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public CreateProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}

public Product createProduct(String name, Money price) {
Product product = Product.create(name, price);
public Product createProduct(String name, Money price, String url) {
Product product = Product.create(name, price, url);

productRepository.save(product);

Expand Down
34 changes: 29 additions & 5 deletions src/main/java/com/example/demo/controllers/ProductController.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,57 @@
import com.example.demo.dtos.CreateProductDto;
import com.example.demo.dtos.ProductListDto;
import com.example.demo.models.Money;
import com.example.demo.utils.ImageStorage;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("products")
@CrossOrigin
public class ProductController {
private final GetProductListService getProductListService;
private final CreateProductService createProductService;
private final ImageStorage imageStorage;

public ProductController(GetProductListService getProductListService,
CreateProductService createProductService) {
CreateProductService createProductService, ImageStorage imageStorage) {
this.getProductListService = getProductListService;
this.createProductService = createProductService;
this.imageStorage = imageStorage;
}

@GetMapping
public ProductListDto list() {
return getProductListService.getProductListDto();
}

@PostMapping
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody CreateProductDto dto) {
public void create(@ModelAttribute CreateProductDto dto) {
String name = dto.name().strip();
Money price = new Money(dto.price());

createProductService.createProduct(name, price);
MultipartFile multipartFile = dto.image();

if (multipartFile == null || multipartFile.isEmpty()) {
throw new NullPointerException();
}
try {
String url = imageStorage.save(multipartFile.getBytes());
createProductService.createProduct(name, price, url);
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}
7 changes: 5 additions & 2 deletions src/main/java/com/example/demo/dtos/CreateProductDto.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.example.demo.dtos;

import org.springframework.web.multipart.MultipartFile;

public record CreateProductDto(
String name,
Long price
String name,
Long price,
MultipartFile image
) {
}
3 changes: 2 additions & 1 deletion src/main/java/com/example/demo/dtos/ProductListDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public List<ProductDto> getProducts() {
public record ProductDto(
String id,
String name,
Long price
Long price,
String image
) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public ProductListDto fetchProductListDto() {
new ProductListDto.ProductDto(
resultSet.getString("id"),
resultSet.getString("name"),
resultSet.getLong("price")
resultSet.getLong("price"),
resultSet.getString("image")
)
);

Expand Down
25 changes: 19 additions & 6 deletions src/main/java/com/example/demo/models/Product.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package com.example.demo.models;

import jakarta.persistence.*;
import jakarta.persistence.AttributeOverride;
import jakarta.persistence.Column;
import jakarta.persistence.Embedded;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

Expand All @@ -12,7 +17,7 @@ public class Product {
@EmbeddedId
private ProductId id;

@Column(name = "name")
@Column(name = "name", nullable = false)
private String name;

@CreationTimestamp
Expand All @@ -22,20 +27,24 @@ public class Product {
private LocalDateTime updatedAt;

@Embedded
@AttributeOverride(name = "value", column = @Column(name = "price"))
@AttributeOverride(name = "value", column = @Column(name = "price", nullable = false))
private Money price;

@Column(name = "image", nullable = false)
private String image;

private Product() {
}

public Product(ProductId id, String name, Money price) {
public Product(ProductId id, String name, Money price, String image) {
this.id = id;
this.name = name;
this.price = price;
this.image = image;
}

public static Product create(String name, Money price) {
return new Product(ProductId.generate(), name, price);
public static Product create(String name, Money price, String image) {
return new Product(ProductId.generate(), name, price, image);
}

public ProductId id() {
Expand All @@ -49,4 +58,8 @@ public String name() {
public Money price() {
return price;
}

public String image() {
return image;
}
}
25 changes: 25 additions & 0 deletions src/main/java/com/example/demo/utils/ImageStorage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.example.demo.utils;

import io.hypersistence.tsid.TSID;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Component
public class ImageStorage {
public String save(byte[] bytes) {
String id = TSID.Factory.getTsid().toString();
String url = "data/" + id + ".jpg";
File file = new File(url);

try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
return url;
}
}
12 changes: 10 additions & 2 deletions src/test/java/com/example/demo/Fixtures.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
package com.example.demo;

import com.example.demo.models.*;
import com.example.demo.models.Cart;
import com.example.demo.models.CartId;
import com.example.demo.models.LineItem;
import com.example.demo.models.LineItemId;
import com.example.demo.models.Money;
import com.example.demo.models.Product;
import com.example.demo.models.ProductId;

import java.util.List;

public class Fixtures {
private static final String filename = "src/test/resources/files/test.jpg";

public static Product product() {
return product(1);
}

public static Product product(int number) {
ProductId productId = new ProductId("012300000000" + number);
return new Product(
productId, "Product #" + number, new Money(123_000L));
productId, "Product #" + number, new Money(123_000L), filename);
}

public static Cart cart() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ class CreateProductServiceTest {

private CreateProductService createProductService;

private final String filename = "src/test/resources/files/test.jpg";

@BeforeEach
void setUp() {
productRepository = mock(ProductRepository.class);
Expand All @@ -27,7 +29,7 @@ void createProduct() {
String name = "제-품";
Money price = new Money(100_000L);

Product product = createProductService.createProduct(name, price);
Product product = createProductService.createProduct(name, price, filename);

assertThat(product.name()).isEqualTo(name);
assertThat(product.price()).isEqualTo(price);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,25 @@
import com.example.demo.application.product.GetProductListService;
import com.example.demo.dtos.ProductListDto;
import com.example.demo.models.Money;
import com.example.demo.utils.ImageStorage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

import java.io.FileInputStream;
import java.util.List;

import static com.example.demo.controllers.helpers.ResultMatchers.contentContains;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(ProductController.class)
Expand All @@ -34,39 +37,43 @@ class ProductControllerTest {
@MockBean
private CreateProductService createProductService;

@MockBean
private ImageStorage imageStorage;

private final String filename = "src/test/resources/files/test.jpg";

@Test
@DisplayName("GET /products")
void list() throws Exception {
ProductListDto.ProductDto productDto =
new ProductListDto.ProductDto("test-id", "제품", 100_000L);
new ProductListDto.ProductDto("test-id", "제품", 100_000L, filename);

given(getProductListService.getProductListDto()).willReturn(
new ProductListDto(List.of(productDto)));
new ProductListDto(List.of(productDto)));

mockMvc.perform(get("/products"))
.andExpect(status().isOk())
.andExpect(contentContains("제품"));
.andExpect(status().isOk())
.andExpect(contentContains("제품"));
}

@Test
@DisplayName("POST /products")
void create() throws Exception {
String json = String.format(
"""
{
"name": "멋진 제품",
"price": %d
}
""",
100_000L
);

mockMvc.perform(post("/products")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(status().isCreated());

MockMultipartFile file = new MockMultipartFile(
"image", "test.jpg", "image/jpeg",
new FileInputStream(filename));

given(imageStorage.save(any())).willReturn(filename);

mockMvc.perform(multipart("/products")
.file(file)
.param("name", "멋진 제품")
.param("price", String.valueOf(100_000L)))
.andExpect(status().isCreated());

verify(createProductService)
.createProduct("멋진 제품", new Money(100_000L));
.createProduct("멋진 제품", new Money(100_000L), filename);
verify(imageStorage).save(any());
}
}
5 changes: 4 additions & 1 deletion src/test/java/com/example/demo/models/ProductTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
import static org.assertj.core.api.Assertions.assertThat;

class ProductTest {
private final String filename = "src/test/resources/files/test.jpg";

@Test
void creation() {
Product product = Product.create("제품명", new Money(123_456L));
Product product = Product.create("제품명", new Money(123_456L), filename);

assertThat(product.id()).isNotNull();
assertThat(product.name()).isEqualTo("제품명");
assertThat(product.price()).isEqualTo(new Money(123_456L));
assertThat(product.image()).isEqualTo(filename);
}
}

0 comments on commit 18a6692

Please sign in to comment.