-
Notifications
You must be signed in to change notification settings - Fork 416
/
BrandService.java
79 lines (66 loc) · 2.72 KB
/
BrandService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.yas.product.service;
import com.yas.product.exception.DuplicatedException;
import com.yas.product.exception.NotFoundException;
import com.yas.product.model.Brand;
import com.yas.product.repository.BrandRepository;
import com.yas.product.utils.Constants;
import com.yas.product.viewmodel.brand.BrandListGetVm;
import com.yas.product.viewmodel.brand.BrandPostVm;
import com.yas.product.viewmodel.brand.BrandVm;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class BrandService {
private final BrandRepository brandRepository;
public BrandService(BrandRepository brandRepository) {
this.brandRepository = brandRepository;
}
public BrandListGetVm getBrands(int pageNo, int pageSize) {
List<BrandVm> brandVms = new ArrayList<>();
Pageable pageable = PageRequest.of(pageNo, pageSize);
Page<Brand> brandPage = brandRepository.findAll(pageable);
List<Brand> brandList = brandPage.getContent();
for (Brand brand : brandList) {
brandVms.add(BrandVm.fromModel(brand));
}
return new BrandListGetVm(
brandVms,
brandPage.getNumber(),
brandPage.getSize(),
(int) brandPage.getTotalElements(),
brandPage.getTotalPages(),
brandPage.isLast()
);
}
public Brand create(BrandPostVm brandPostVm) {
validateExistedName(brandPostVm.name(), null);
return brandRepository.save(brandPostVm.toModel());
}
public Brand update(BrandPostVm brandPostVm, Long id) {
validateExistedName(brandPostVm.name(), id);
Brand brand = brandRepository
.findById(id)
.orElseThrow(() -> new NotFoundException(Constants.ErrorCode.BRAND_NOT_FOUND, id));
brand.setSlug(brandPostVm.slug());
brand.setName(brandPostVm.name());
brand.setPublished(brandPostVm.isPublish());
return brandRepository.save(brand);
}
private void validateExistedName(String name, Long id) {
if (checkExistedName(name, id)) {
throw new DuplicatedException(Constants.ErrorCode.NAME_ALREADY_EXITED, name);
}
}
private boolean checkExistedName(String name, Long id) {
return brandRepository.findExistedName(name, id) != null;
}
public List<BrandVm> getBrandsByIds(List<Long> ids) {
return brandRepository.findAllById(ids).stream().map(BrandVm::fromModel).toList();
}
}