Commit 2386cd22 authored by Vladimir Trubachoff's avatar Vladimir Trubachoff

Backend: code refactoring

parent 699282d6
......@@ -8,8 +8,8 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
......@@ -31,6 +31,6 @@ public class Goods {
@Column(name = "price")
private double price;
@OneToMany(mappedBy = "goods", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<OrderLine> orderLines = new ArrayList<>();
@OneToMany(mappedBy = "goods", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<OrderLine> orderLines = new HashSet<>();
}
......@@ -10,8 +10,8 @@ import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
......@@ -38,6 +38,6 @@ public class Order {
@Column(name = "address")
private String address;
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<OrderLine> orderLines = new ArrayList<>();
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
private Set<OrderLine> orderLines = new HashSet<>();
}
package com.example.testj.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.*;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
......@@ -22,13 +21,12 @@ public class OrderLine {
@Column(name = "id")
private Long id;
@NotNull
@JsonIgnore
@JsonIgnoreProperties(value = "orderLines")
@ManyToOne
@JoinColumn(name = "order_id")
private Order order;
@NotNull
@JsonIgnoreProperties(value = "orderLines")
@ManyToOne
@JoinColumn(name = "goods_id")
private Goods goods;
......
......@@ -2,16 +2,18 @@ package com.example.testj.exception;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Getter
@Setter
public class ApiError {
private final Date timestamp;
private HttpStatus status;
private HttpStatusCode status;
private String message;
private List<Map<String, String>> errors;
......@@ -19,7 +21,7 @@ public class ApiError {
timestamp = new Date();
}
public ApiError(HttpStatus status, String message, List<Map<String, String>> errors) {
public ApiError(HttpStatusCode status, String message, List<Map<String, String>> errors) {
super();
timestamp = new Date();
this.status = status;
......@@ -27,12 +29,11 @@ public class ApiError {
this.errors = errors;
}
public ApiError(HttpStatus status, String message, String error) {
public ApiError(HttpStatusCode status, String message, String error) {
super();
timestamp = new Date();
this.status = status;
this.message = message;
errors = new ArrayList<>((Collection) Map.of("message", error));
errors = List.of(Map.of("message", error));
}
}
\ No newline at end of file
......@@ -5,4 +5,12 @@ import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final String message = "Resource not found";
public ResourceNotFoundException() {
super(message);
}
public ResourceNotFoundException(String message) {
super(message);
}
}
......@@ -22,18 +22,6 @@ public class RestResponseEntityExceptionHandler
extends ResponseEntityExceptionHandler {
@ExceptionHandler({ DateTimeParseException.class })
public ResponseEntity<Object> handleDateTimeParseException(Exception ex, WebRequest request) {
List<Map<String, String>> errors = List.of(Map.of("field", "date", "message", ex.getMessage()));
ApiError body = new ApiError(HttpStatus.BAD_REQUEST, "Date parse error", errors);
return new ResponseEntity<>(body, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
// 500
@ExceptionHandler({ Exception.class })
public ResponseEntity<Object> handleAll(Exception ex, WebRequest request) {
final ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), "error occurred");
return new ResponseEntity<>(apiError, new HttpHeaders(), apiError.getStatus());
}
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
......@@ -43,7 +31,7 @@ public class RestResponseEntityExceptionHandler
.stream()
.map(err -> Map.of("field", err.getField(), "message", err.getDefaultMessage()))
.collect(Collectors.toList());
ApiError body = new ApiError(HttpStatus.BAD_REQUEST, ex.getBody().getDetail(), errors);
ApiError body = new ApiError(status, ex.getBody().getDetail(), errors);
return handleExceptionInternal(ex, body, headers, status, request);
}
......
package com.example.testj.service;
import com.example.testj.domain.OrderLine;
import com.example.testj.exception.ResourceNotFoundException;
import com.example.testj.service.dto.OrderLineDto;
import com.example.testj.service.dto.OrderLineRequestDto;
......@@ -10,7 +9,7 @@ public interface OrderLineService {
OrderLineDto createOrderLine(OrderLineRequestDto request);
OrderLineDto updateOrderLine(OrderLine orderLine);
OrderLineDto updateOrderLineCount(Long id, int count) throws ResourceNotFoundException;
void deleteOrderLine(Long id);
}
......@@ -28,11 +28,10 @@ public class OrderLineServiceImpl implements OrderLineService {
@Override
public OrderLineDto createOrderLine(OrderLineRequestDto request) {
Order order = orderMapper.toEntity(orderService.getOrder(request.getOrderId()));
Goods goods = goodsMapper.toEntity(goodsService.getGoods(request.getGoodsId()));
OrderLine orderLine = new OrderLine();
Order order = orderMapper.toEntity(orderService.getOrder(request.getOrderId()));
orderLine.setOrder(order);
Goods goods = goodsMapper.toEntity(goodsService.getGoods(request.getGoodsId()));
orderLine.setGoods(goods);
orderLine.setCount(request.getCount());
......@@ -40,8 +39,9 @@ public class OrderLineServiceImpl implements OrderLineService {
}
@Override
public OrderLineDto updateOrderLine(OrderLine orderLine) {
orderLineRepository.findById(orderLine.getId()).orElseThrow(ResourceNotFoundException::new);
public OrderLineDto updateOrderLineCount(Long id, int count) {
OrderLine orderLine = orderLineRepository.findById(id).orElseThrow(ResourceNotFoundException::new);
orderLine.setCount(count);
return orderLineMapper.toDto(orderLineRepository.save(orderLine));
}
......
......@@ -3,9 +3,8 @@ package com.example.testj.service.mapper;
import com.example.testj.domain.Order;
import com.example.testj.service.dto.OrderDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(componentModel = "spring")
public interface OrderMapper {
OrderDto toDto(Order order);
Order toEntity(OrderDto orderDto);
......
......@@ -37,9 +37,7 @@ public class OrderLineController {
@PutMapping("/{id}")
public OrderLineDto update(@PathVariable Long id, @Valid @RequestBody OrderLineUpdateRequestDto request) {
OrderLineDto orderLineDto = orderLineService.getOrderLine(id);
orderLineDto.setCount(request.getCount());
return orderLineService.updateOrderLine(orderLineMapper.toEntity(orderLineDto));
return orderLineService.updateOrderLineCount(id, request.getCount());
}
@DeleteMapping("/{id}")
......
......@@ -11,3 +11,5 @@ spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false
logging.level.org.springframework.web=INFO
server.error.include-stacktrace=never
......@@ -103,7 +103,7 @@ public class OrderLineServiceTest {
// when
when(orderLineRepository.findById(id)).thenReturn(Optional.of(orderLine));
when(orderLineRepository.save(any(OrderLine.class))).thenReturn(result);
OrderLineDto updatedOrderLine = orderLineService.updateOrderLine(orderLine);
OrderLineDto updatedOrderLine = orderLineService.updateOrderLineCount(id, count);
// then
assertEquals(count, updatedOrderLine.getCount());
verify(orderLineRepository, times(1)).save(any(OrderLine.class));
......
package com.example.testj.web.rest;
import com.example.testj.domain.OrderLine;
import com.example.testj.exception.ResourceNotFoundException;
import com.example.testj.service.OrderLineService;
import com.example.testj.service.dto.GoodsDto;
......@@ -88,7 +87,7 @@ public class OrderLineControllerTest {
String body = new ObjectMapper().writeValueAsString(request);
when(orderLineService.getOrderLine(id)).thenReturn(orderLineDto);
when(orderLineService.updateOrderLine(any(OrderLine.class))).thenReturn(orderLineDto);
when(orderLineService.updateOrderLineCount(id, orderLineDto.getCount())).thenReturn(orderLineDto);
mvc.perform(put("/api/order-line/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment