|
| 1 | +package ro.unibuc.lab04.main.service; |
| 2 | + |
| 3 | +import org.springframework.stereotype.Service; |
| 4 | +import ro.unibuc.lab04.main.dto.DishDto; |
| 5 | +import ro.unibuc.lab04.main.model.Dish; |
| 6 | +import ro.unibuc.lab04.main.repo.DishRepository; |
| 7 | + |
| 8 | +import java.util.List; |
| 9 | +import java.util.Optional; |
| 10 | + |
| 11 | +@Service |
| 12 | +public class SimpleDishService implements DishService { |
| 13 | + |
| 14 | + private final DishRepository dishRepo; |
| 15 | + |
| 16 | + public SimpleDishService(DishRepository dishRepo) { |
| 17 | + this.dishRepo = dishRepo; |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public DishDto addDish(DishDto dish) { |
| 22 | + final var savedDish = dishRepo.add(new Dish(dish.name(), dish.price())); |
| 23 | + return mapToDto(savedDish); |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public List<DishDto> getAll() { |
| 28 | + return dishRepo.findAll().stream() |
| 29 | + .map(SimpleDishService::mapToDto) |
| 30 | + .toList(); |
| 31 | + } |
| 32 | + |
| 33 | + @Override |
| 34 | + public Optional<DishDto> getById(int dishId) { |
| 35 | + return dishRepo.findById(dishId).map(SimpleDishService::mapToDto); |
| 36 | + } |
| 37 | + |
| 38 | + @Override |
| 39 | + public Optional<DishDto> update(DishDto dish) { |
| 40 | + return Optional.ofNullable(dishRepo.update(mapToModel(dish))).map(SimpleDishService::mapToDto); |
| 41 | + } |
| 42 | + |
| 43 | + @Override |
| 44 | + public void deleteById(int dishId) { |
| 45 | + dishRepo.removeById(dishId); |
| 46 | + } |
| 47 | + |
| 48 | + private static DishDto mapToDto(Dish dish) { |
| 49 | + return new DishDto(dish.id(), dish.name(), dish.price()); |
| 50 | + } |
| 51 | + |
| 52 | + private static Dish mapToModel(DishDto dto) { |
| 53 | + return new Dish(dto.id(), dto.name(), dto.price()); |
| 54 | + } |
| 55 | +} |
0 commit comments