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

Implemented CRUD operations for Product Module #45

Merged
merged 5 commits into from
Oct 19, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ build/

### VS Code ###
.vscode/

### ENV ###
*.env
3 changes: 3 additions & 0 deletions product/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,6 @@ build/

### VS Code ###
.vscode/

### ENV ###
.env
14 changes: 14 additions & 0 deletions product/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>me.paulschwarz</groupId>
<artifactId>spring-dotenv</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
23 changes: 23 additions & 0 deletions product/src/main/java/com/fjb/product/config/Security.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.fjb.product.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class Security {
@Bean
@SuppressWarnings("java:S4502")
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(request -> request
.requestMatchers("/api/**").permitAll())
.csrf(csrf -> csrf
.ignoringRequestMatchers("/api/**"))
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,25 @@

import com.fjb.product.dto.request.ProductCreateDto;
import com.fjb.product.dto.response.ProductResponseDto;
import com.fjb.product.exception.ErrorCreatingEntry;
import com.fjb.product.exception.ProductNotFoundException;
import com.fjb.product.service.ProductService;
import java.math.BigDecimal;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("/api/product")
@RequiredArgsConstructor
Expand All @@ -19,8 +29,86 @@ public class ProductController {
private final ProductService productService;

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ProductResponseDto createProduct(@RequestBody ProductCreateDto productCreateDto) {
return productService.createProduct(productCreateDto);
public ResponseEntity<ProductResponseDto> createProduct(@RequestBody ProductCreateDto productCreateDto) {
try {
ProductResponseDto productResponseDto = productService.createProduct(productCreateDto);
if (productResponseDto == null) {
throw new ErrorCreatingEntry("Could not create entry");
} else {
return new ResponseEntity<>(productResponseDto, HttpStatus.CREATED);
}
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}

@GetMapping
public ResponseEntity<List<ProductResponseDto>> getAllProducts() {
try {
List<ProductResponseDto> list = productService.getAllProducts();
if (list.isEmpty()) {
throw new ProductNotFoundException("No Entries found!");
} else {
return new ResponseEntity<>(list, HttpStatus.OK);
}
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@GetMapping("/id/{id}")
public ResponseEntity<ProductResponseDto> getProductById(@PathVariable Long id) {
try {
ProductResponseDto productResponseDto = productService.getProduct(id);
if (productResponseDto == null) {
throw new ProductNotFoundException("No Entry found");
}
return new ResponseEntity<>(productResponseDto, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}

@PutMapping("/id/{id}")
public ResponseEntity<ProductResponseDto> updateProduct(
@PathVariable Long id, @RequestBody ProductCreateDto newProductCreateDto
) {
try {
ProductResponseDto existingProduct = productService.getProduct(id);
if (existingProduct != null) {
String newName = newProductCreateDto.getName();
String newDescription = newProductCreateDto.getDescription();
BigDecimal newPrice = newProductCreateDto.getPrice();

existingProduct.setName(
newName != null && !newName.isEmpty()
? newName : existingProduct.getName()
);
existingProduct.setDescription(
newDescription != null && !newDescription.isEmpty()
? newDescription : existingProduct.getDescription()
);
existingProduct.setPrice(
newPrice != null
? newPrice : existingProduct.getPrice()
);
ProductResponseDto updated = productService.saveExistingProduct(existingProduct);
return new ResponseEntity<>(updated, HttpStatus.CREATED);
} else {
throw new ProductNotFoundException("Entry not found");
}
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}

@DeleteMapping("/id/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
try {
productService.deleteProductById(id);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
@NoArgsConstructor
@AllArgsConstructor
public class ProductResponseDto {
private String id;
private Long id;
private String name;
private String description;
private BigDecimal price;
Expand Down
5 changes: 4 additions & 1 deletion product/src/main/java/com/fjb/product/entity/Product.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.fjb.product.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.math.BigDecimal;
Expand All @@ -19,7 +21,8 @@
@AllArgsConstructor
public class Product {
@Id
private String id;
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private BigDecimal price;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.fjb.product.exception;

public class ErrorCreatingEntry extends RuntimeException {
public ErrorCreatingEntry(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.fjb.product.exception;

public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ public interface ProductMapper {
Product toProduct(ProductCreateDto productCreateDto);

ProductResponseDto toProductResponseDto(Product product);

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.fjb.product.repository;

import com.fjb.product.entity.Product;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, String> {
Product findById(Long id);

List<Product> findAllByOrderByIdAsc();
}
39 changes: 36 additions & 3 deletions product/src/main/java/com/fjb/product/service/ProductService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,53 @@
import com.fjb.product.entity.Product;
import com.fjb.product.mapper.ProductMapper;
import com.fjb.product.repository.ProductRepository;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ProductService {

private final ProductMapper productMapper;
private final ProductRepository productRepository;

public ProductResponseDto createProduct(ProductCreateDto productCreateDto) {
Product product = productMapper.toProduct(productCreateDto);
return productMapper.toProductResponseDto(productRepository.save(product));
product = productRepository.save(product);
return productMapper.toProductResponseDto(product);
}

public List<ProductResponseDto> getAllProducts() {
List<Product> list = productRepository.findAllByOrderByIdAsc();
List<ProductResponseDto> reqList = new ArrayList<>();
for (Product product : list) {
reqList.add(productMapper.toProductResponseDto(product));
}
return reqList;
}

public ProductResponseDto getProduct(Long id) {
Product product = productRepository.findById(id);
return productMapper.toProductResponseDto(product);
}

public ProductResponseDto saveExistingProduct(ProductResponseDto productResponseDto) {
Product existingProduct = productRepository.findById(productResponseDto.getId());
if (existingProduct == null) {
throw new IllegalArgumentException("Product not found");
} else {
existingProduct.setName(productResponseDto.getName());
existingProduct.setDescription(productResponseDto.getDescription());
existingProduct.setPrice(productResponseDto.getPrice());
Product product = productRepository.save(existingProduct);
return productMapper.toProductResponseDto(product);
}
}

public void deleteProductById(Long id) {
productRepository.deleteById(String.valueOf(id));
}
}
3 changes: 3 additions & 0 deletions product/src/main/resources/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
POSTGRES_USERNAME=
POSTGRES_PASSWORD=
POSTGRES_DATABASE_URL="jdbc:postgresql://localhost:5432/product"
6 changes: 3 additions & 3 deletions product/src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
spring.application.name=product

spring.datasource.url=jdbc:postgresql://localhost:5432/product
spring.datasource.username=admin
spring.datasource.password=admin
spring.datasource.url=${POSTGRES_DATABASE_URL}
spring.datasource.username=${POSTGRES_USERNAME}
spring.datasource.password=${POSTGRES_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver

# JPA & Hibernate settings
Expand Down
Loading