Skip to content

Commit

Permalink
refactor: using mapstruct
Browse files Browse the repository at this point in the history
  • Loading branch information
lcaohoanq committed Dec 13, 2024
1 parent f48ede3 commit c1d4e4c
Show file tree
Hide file tree
Showing 22 changed files with 219 additions and 44 deletions.
12 changes: 12 additions & 0 deletions SPCServer/springboot/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,18 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.5.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.lcaohoanq.shoppe.metadata.PaginationMeta;
import java.util.Collection;
import java.util.List;
import lombok.NoArgsConstructor;

Expand All @@ -14,12 +15,12 @@
"is_success",
})
@NoArgsConstructor
public class PageResponse<T> extends ApiResponse<List<T>> {
public class PageResponse<T> extends ApiResponse<Collection<T>> {
@JsonProperty("pagination")
private PaginationMeta pagination;

private PageResponse(Integer statusCode, String message, String reason,
Boolean isSuccess, List<T> data, PaginationMeta pagination) {
Boolean isSuccess, Collection<T> data, PaginationMeta pagination) {
super(statusCode, message, reason, isSuccess, data);
this.pagination = pagination;
}
Expand All @@ -33,7 +34,7 @@ public static class PageResponseBuilder<T> {
private String message;
private String reason;
private Boolean isSuccess;
private List<T> data;
private Collection<T> data;
private PaginationMeta pagination;

PageResponseBuilder() {
Expand All @@ -59,7 +60,7 @@ public PageResponseBuilder<T> isSuccess(Boolean isSuccess) {
return this;
}

public PageResponseBuilder<T> data(List<T> data) {
public PageResponseBuilder<T> data(Collection<T> data) {
this.data = data;
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import com.lcaohoanq.shoppe.api.ApiResponse;
import com.lcaohoanq.shoppe.domain.token.TokenService;
import com.lcaohoanq.shoppe.domain.user.IUserService;
import com.lcaohoanq.shoppe.mapper.UserMapper;
import com.lcaohoanq.shoppe.util.DTOConverter;
import com.lcaohoanq.shoppe.util.Identifiable;
import com.lcaohoanq.shoppe.constant.MessageKey;
Expand Down Expand Up @@ -43,6 +44,7 @@ public class AuthController implements Identifiable, DTOConverter {
private final TokenService tokenService;
private final HttpServletRequest request;
private final IAuthService authService;
private final UserMapper userMapper;

@Timed(
value = "custom.login.requests",
Expand Down Expand Up @@ -105,7 +107,7 @@ public ResponseEntity<ApiResponse<UserResponse>> createUser(
localizationUtils.getLocalizedMessage(MessageKey.REGISTER_SUCCESSFULLY))
.statusCode(HttpStatus.CREATED.value())
.isSuccess(true)
.data(toUserResponse(user))
.data(userMapper.toUserResponse(user))
.build());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.lcaohoanq.shoppe.domain.role.RoleService;
import com.lcaohoanq.shoppe.domain.token.TokenService;
import com.lcaohoanq.shoppe.domain.user.UserService;
import com.lcaohoanq.shoppe.mapper.UserMapper;
import com.lcaohoanq.shoppe.util.DTOConverter;
import com.lcaohoanq.shoppe.constant.MessageKey;
import io.reactivex.rxjava3.core.Single;
Expand Down Expand Up @@ -69,6 +70,7 @@ public class AuthService implements IAuthService, DTOConverter {
private final WalletRepository walletRepository;
private final CartRepository cartRepository;
private final CartService cartService;
private final UserMapper userMapper;

@Override
@Transactional
Expand Down Expand Up @@ -182,7 +184,7 @@ public UserResponse getUserDetailsFromToken(String token) throws Exception {
Optional<User> user = userRepository.findByEmail(email);

if (user.isPresent()) {
return toUserResponse(user.get());
return userMapper.toUserResponse(user.get());
} else {
throw new Exception(
localizationUtils.getLocalizedMessage(MessageKey.USER_NOT_FOUND)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ public class Category extends BaseEntity {
private String name;

@OneToMany(mappedBy = "category")
private Set<Subcategory> subcategory;
private Set<Subcategory> subcategories;

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import com.lcaohoanq.shoppe.exception.CategoryNotFoundException;
import com.lcaohoanq.shoppe.base.exception.DataAlreadyExistException;
import com.lcaohoanq.shoppe.base.exception.DataNotFoundException;
import com.lcaohoanq.shoppe.mapper.CategoryMapper;
import com.lcaohoanq.shoppe.mapper.ProductMapper;
import com.lcaohoanq.shoppe.util.DTOConverter;
import com.lcaohoanq.shoppe.util.PaginationConverter;
import java.util.HashSet;
Expand All @@ -25,12 +27,13 @@

@Service
@RequiredArgsConstructor
public class CategoryService implements ICategoryService, DTOConverter,
PaginationConverter {
public class CategoryService implements ICategoryService, PaginationConverter {

private final CategoryRepository categoryRepository;
private final SubcategoryRepository subcategoryRepository;
private final ProductRepository productRepository;
private final CategoryMapper categoryMapper;
private final ProductMapper productMapper;

@Override
public List<CategoryResponse> createCategory(CategoryDTO category)
Expand All @@ -49,7 +52,7 @@ public List<CategoryResponse> createCategory(CategoryDTO category)
});

return categories.stream()
.map(name -> toCategoryResponse(categoryRepository.findByName(name).get()))
.map(name -> categoryMapper.toCategoryResponse(categoryRepository.findByName(name).get()))
.collect(Collectors.toList());
}

Expand All @@ -58,13 +61,13 @@ public CategoryResponse getById(long id) throws DataNotFoundException {
Category category = categoryRepository.findById(id)
.orElseThrow(() -> new CategoryNotFoundException("Category not found"));

return toCategoryResponse(category);
return categoryMapper.toCategoryResponse(category);
}

@Override
public List<CategoryResponse> getAllCategories() {
return categoryRepository.findAll().stream()
.map(this::toCategoryResponse)
.map(categoryMapper::toCategoryResponse)
.sorted((o1, o2) -> (int) (o1.id() - o2.id()))
.toList();
}
Expand Down Expand Up @@ -115,7 +118,7 @@ public CreateNewSubcategoryResponse createSubCategory(SubcategoryDTO subcategory
.build());
});

return new CreateNewSubcategoryResponse(toCategoryResponse(category));
return new CreateNewSubcategoryResponse(categoryMapper.toCategoryResponse(category));


}
Expand All @@ -129,8 +132,9 @@ public PageResponse<ProductResponse> findByCategoryId(Long categoryId, Pageable
return mapPageResponse(
productPage,
pageable,
this::toProductResponse,
"Get products by category successfully"
productMapper::toProductResponse,
"Get products by category successfully",
HashSet::new
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.lcaohoanq.shoppe.exception.CategoryNotFoundException;
import com.lcaohoanq.shoppe.exception.InvalidParamException;
import com.lcaohoanq.shoppe.exception.MalformBehaviourException;
import com.lcaohoanq.shoppe.mapper.ProductMapper;
import com.lcaohoanq.shoppe.metadata.MediaMeta;
import com.lcaohoanq.shoppe.util.DTOConverter;
import com.lcaohoanq.shoppe.util.PaginationConverter;
Expand All @@ -23,17 +24,18 @@

@Service
@RequiredArgsConstructor
public class ProductService implements IProductService, DTOConverter, PaginationConverter {
public class ProductService implements IProductService, PaginationConverter {

private final ProductRepository productRepository;
private final CategoryRepository categoryRepository;
private final UserRepository userRepository;
private final ProductImageRepository productImageRepository;
private final ProductMapper productMapper;

@Override
public PageResponse<ProductResponse> getAll(PageRequest pageRequest) {
Page<Product> productsPage = productRepository.findAll(pageRequest);
return mapPageResponse(productsPage, pageRequest, this::toProductResponse, "Get all products successfully");
return mapPageResponse(productsPage, pageRequest, productMapper::toProductResponse, "Get all products successfully");
}

@Override
Expand All @@ -42,7 +44,7 @@ public ProductResponse getById(long id) {
if(product.orElseThrow(() -> new DataNotFoundException("Product not exist")) == null){
throw new DataNotFoundException("Product not exist");
}
return toProductResponse(product.get());
return productMapper.toProductResponse(product.get());
}

@Transactional
Expand Down Expand Up @@ -84,7 +86,7 @@ public ProductResponse create(ProductDTO productDTO) {
.isActive(true) //default active
.build();

return toProductResponse(productRepository.save(newProduct));
return productMapper.toProductResponse(productRepository.save(newProduct));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.lcaohoanq.shoppe.domain.role;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.lcaohoanq.shoppe.enums.UserRole;
import com.lcaohoanq.shoppe.base.entity.BaseEntity;
import jakarta.persistence.Column;
Expand All @@ -26,6 +28,7 @@
@Table(name = "roles")
@Entity
@SuperBuilder

public class Role extends BaseEntity {

@Id
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.lcaohoanq.shoppe.enums.UserRole;
import java.time.LocalDateTime;

@JsonPropertyOrder(
{
"id",
"name",
"created_at",
"updated_at"
}
)
public record RoleResponse(
@JsonProperty("id") Long id,
@JsonProperty("name") UserRole name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.lcaohoanq.shoppe.exception.MalformDataException;
import com.lcaohoanq.shoppe.base.exception.DataAlreadyExistException;
import com.lcaohoanq.shoppe.base.exception.DataNotFoundException;
import com.lcaohoanq.shoppe.mapper.RoleMapper;
import com.lcaohoanq.shoppe.util.DTOConverter;
import java.util.Arrays;
import java.util.List;
Expand All @@ -12,15 +13,16 @@

@Service
@RequiredArgsConstructor
public class RoleService implements IRoleService, DTOConverter {
public class RoleService implements IRoleService {

private final RoleRepository roleRepository;
private final RoleMapper roleMapper;

@Override
public List<RoleResponse> getAllRoles() {
return roleRepository.findAll()
.stream()
.map(this::toRoleResponse)
.map(roleMapper::toRoleResponse)
.toList();
}

Expand All @@ -39,7 +41,7 @@ public RoleResponse createRole(RoleDTO roleDTO) {
.userRole(roleDTO.userRole())
.build();

return toRoleResponse(roleRepository.save(newRole));
return roleMapper.toRoleResponse(roleRepository.save(newRole));
}

@Override
Expand All @@ -60,7 +62,7 @@ public void deleteRole(Long id) {
@Override
public RoleResponse getRoleById(Long id) {
return roleRepository.findById(id)
.map(this::toRoleResponse)
.map(roleMapper::toRoleResponse)
.orElseThrow(() -> new DataNotFoundException("Role with id " + id + " not found"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ public class User extends BaseEntity implements UserDetails {

@Enumerated(EnumType.STRING)
@Column(name="status")
@JsonProperty("status")
private UserStatus status;

@Column(name="date_of_birth")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import com.lcaohoanq.shoppe.exception.MalformDataException;
import com.lcaohoanq.shoppe.exception.MethodArgumentNotValidException;
import com.lcaohoanq.shoppe.domain.token.TokenService;
import com.lcaohoanq.shoppe.mapper.UserMapper;
import com.lcaohoanq.shoppe.util.DTOConverter;
import com.lcaohoanq.shoppe.constant.MessageKey;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.Objects;
import javax.print.event.PrintJobAttributeEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
Expand Down Expand Up @@ -42,6 +44,7 @@ public class UserController implements DTOConverter {
private final TokenService tokenService;
private final HttpServletRequest request;
private final JwtTokenUtils jwtTokenUtils;
private final UserMapper userMapper;

@GetMapping("")
//@PreAuthorize("permitAll()")
Expand All @@ -57,7 +60,7 @@ public ResponseEntity<PageResponse<UserResponse>> fetchUser(
public ResponseEntity<UserResponse> getUserById(
@PathVariable Long id
) {
return ResponseEntity.ok(toUserResponse(userService.findUserById(id)));
return ResponseEntity.ok(userMapper.toUserResponse(userService.findUserById(id)));
}

@PostMapping("/details")
Expand All @@ -66,7 +69,7 @@ public ResponseEntity<UserResponse> takeUserDetailsFromToken() throws Exception
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
return ResponseEntity.ok(
toUserResponse(userService.findByUsername(userDetails.getUsername())));
userMapper.toUserResponse(userService.findByUsername(userDetails.getUsername())));
}

@PutMapping("/details/{userId}")
Expand All @@ -90,7 +93,7 @@ public ResponseEntity<ApiResponse<UserResponse>> updateUserDetails(
return ResponseEntity.ok(
ApiResponse.<UserResponse>builder()
.message(MessageKey.UPDATE_USER_SUCCESSFULLY)
.data(toUserResponse(userService.updateUser(userId, updatedUserDTO)))
.data(userMapper.toUserResponse(userService.updateUser(userId, updatedUserDTO)))
.isSuccess(true)
.statusCode(HttpStatus.OK.value())
.build());
Expand Down
Loading

0 comments on commit c1d4e4c

Please sign in to comment.