Skip to content

Commit

Permalink
refactor: spaceType, sportType, spotType - controllers refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ShulV committed Dec 10, 2023
1 parent 25507f5 commit ba632f9
Show file tree
Hide file tree
Showing 9 changed files with 169 additions and 101 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ public ResponseEntity<ApiResponse<RegionDto>> getAll() {

@Operation(
summary = "Получение списка всех регионов по стране",
description = "Позволяет пользователю получить перечень всех регионов, находящихся в определенной стране по ее id"
description = "Позволяет пользователю получить перечень всех регионов, находящихся в определенной стране по ее id" +
"(БОЛЬШАЯ НАГРУЗКА НА СЕТЬ! СНАЧАЛА НУЖНО ПОЛУЧАТЬ СПИСОК РЕГИОНОВ ДЛЯ ОПРЕДЕЛЕННОЙ СТРАНЫ!)"
)
@GetMapping("/by-country/{id}")
public ResponseEntity<ApiResponse<RegionDto>> getByCountryId(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
package com.shulpov.spots_app.spot_references.controllers;

import com.shulpov.spots_app.common.ApiResponse;
import com.shulpov.spots_app.common.ApiResponseStatus;
import com.shulpov.spots_app.spot_references.dto.SpaceTypeDto;
import com.shulpov.spots_app.spot_references.models.SpaceType;
import com.shulpov.spots_app.spot_references.services.SpaceTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

/**
* @author Shulpov Victor
Expand All @@ -35,22 +36,29 @@ public class SpaceTypeController {
description = "Позволяет пользователю получить все типы помещений"
)
@GetMapping("/all")
public List<SpaceTypeDto> getAllSpaceTypes() {
return spaceTypeService.getAllDto();
public ResponseEntity<ApiResponse<SpaceTypeDto>> getAllSpaceTypes() {
ApiResponse<SpaceTypeDto> response = new ApiResponse<>();
response.setDataList(spaceTypeService.getAllDto());
response.setCustomStatus(ApiResponseStatus.SUCCESS);
return ResponseEntity.ok(response);
}

@Operation(
summary = "Получение конкретного типа помещения",
description = "Позволяет пользователю получить тип помещения по id"
)
@GetMapping("/{id}")
public SpaceType getSpaceType(@PathVariable(name = "id") Integer id) throws NoSuchElementException {
Optional<SpaceType> spaceTypeOpt = spaceTypeService.getById(id);
if(spaceTypeOpt.isPresent()) {
return spaceTypeOpt.get();
} else {
logger.atError().log("No space type with such id");
throw new NoSuchElementException("No space type with such id");
public ResponseEntity<ApiResponse<SpaceTypeDto>> getSpaceType(
@Parameter(description = "Идентификатор типа помещения", example = "1")
@PathVariable(name = "id") Integer id) {
ApiResponse<SpaceTypeDto> response = new ApiResponse<>();
try {
response.setData(spaceTypeService.getDtoById(id));
response.setCustomStatus(ApiResponseStatus.SUCCESS);
} catch (NoSuchElementException e) {
response.setCustomStatus(ApiResponseStatus.CLIENT_ERROR);
response.setMessage("No space type with id=" + id);
}
return ResponseEntity.ok(response);
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
package com.shulpov.spots_app.spot_references.controllers;

import com.shulpov.spots_app.common.ApiResponse;
import com.shulpov.spots_app.common.ApiResponseStatus;
import com.shulpov.spots_app.spot_references.dto.SportTypeDto;
import com.shulpov.spots_app.spot_references.models.SportType;
import com.shulpov.spots_app.spot_references.services.SportTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

/**
* @author Shulpov Victor
Expand All @@ -28,29 +27,35 @@
@RequiredArgsConstructor
public class SportTypeController {
private final SportTypeService sportTypeService;
private final Logger logger = LoggerFactory.getLogger(SportTypeController.class);

@Operation(
summary = "Получение всех типов спорта",
description = "Позволяет пользователю получить все типы спотов"
)
@GetMapping("/all")
public List<SportTypeDto> getAllSportTypes() {
return sportTypeService.getAllDto();
public ResponseEntity<ApiResponse<SportTypeDto>> getAllSportTypes() {
ApiResponse<SportTypeDto> response = new ApiResponse<>();
response.setDataList(sportTypeService.getAllDto());
response.setCustomStatus(ApiResponseStatus.SUCCESS);
return ResponseEntity.ok(response);
}

@Operation(
summary = "Получение конкретного типа спорта",
description = "Позволяет пользователю получить тип спорта по id"
)
@GetMapping("/{id}")
public SportType getSportType(@PathVariable(name = "id") Integer id) throws NoSuchElementException {
Optional<SportType> sportTypeOpt = sportTypeService.getById(id);
if(sportTypeOpt.isPresent()) {
return sportTypeOpt.get();
} else {
logger.atError().log("No sport type with such id");
throw new NoSuchElementException("No sport type with such id");
public ResponseEntity<ApiResponse<SportTypeDto>> getSportType(
@Parameter(description = "Идентификатор типа спорта", example = "1")
@PathVariable(name = "id") Integer id) {
ApiResponse<SportTypeDto> response = new ApiResponse<>();
try {
response.setData(sportTypeService.getDtoById(id));
response.setCustomStatus(ApiResponseStatus.SUCCESS);
} catch (NoSuchElementException e) {
response.setCustomStatus(ApiResponseStatus.CLIENT_ERROR);
response.setMessage("No sport type with id=" + id);
}
return ResponseEntity.ok(response);
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
package com.shulpov.spots_app.spot_references.controllers;

import com.shulpov.spots_app.common.ApiResponse;
import com.shulpov.spots_app.common.ApiResponseStatus;
import com.shulpov.spots_app.spot_references.dto.SpotTypeDto;
import com.shulpov.spots_app.spot_references.models.SpotType;
import com.shulpov.spots_app.spot_references.services.SpotTypeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

/**
* @author Shulpov Victor
Expand All @@ -24,35 +24,38 @@
@Tag(name="Контроллер типов мест для катания (справочник)", description="Выдает типы мест для катания")
@RestController
@RequestMapping("/api/v1/spot-types")
@RequiredArgsConstructor
public class SpotTypeController {
private final SpotTypeService spotTypeService;
private final Logger logger = LoggerFactory.getLogger(SpotTypeController.class);

public SpotTypeController(SpotTypeService spotTypeService) {
this.spotTypeService = spotTypeService;
}

@Operation(
summary = "Получение всех типов спотов",
description = "Позволяет пользователю получить все типы спотов"
)
@GetMapping("/all")
public List<SpotTypeDto> getAllSpots() {
return spotTypeService.getAllDto();
public ResponseEntity<ApiResponse<SpotTypeDto>> getAllSpots() {
ApiResponse<SpotTypeDto> response = new ApiResponse<>();
response.setDataList(spotTypeService.getAllDto());
response.setCustomStatus(ApiResponseStatus.SUCCESS);
return ResponseEntity.ok(response);
}

@Operation(
summary = "Получение конкретного типа спота",
description = "Позволяет пользователю получить тип спота по его id"
)
@GetMapping("/{id}")
public SpotType getSpotType(@PathVariable(name = "id") Integer id) throws NoSuchElementException {
Optional<SpotType> spotTypeOpt = spotTypeService.getById(id);
if(spotTypeOpt.isPresent()) {
return spotTypeOpt.get();
} else {
logger.atError().log("No spot type with such id");
throw new NoSuchElementException("No spot type with such id");
public ResponseEntity<ApiResponse<SpotTypeDto>> getSpotType(
@Parameter(description = "Идентификатор типа спота", example = "1")
@PathVariable(name = "id") Integer id) throws NoSuchElementException {
ApiResponse<SpotTypeDto> response = new ApiResponse<>();
try {
response.setData(spotTypeService.getDtoById(id));
response.setCustomStatus(ApiResponseStatus.SUCCESS);
} catch (NoSuchElementException e) {
response.setCustomStatus(ApiResponseStatus.CLIENT_ERROR);
response.setMessage("No spot type with id=" + id);
}
return ResponseEntity.ok(response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@

import com.shulpov.spots_app.spot_references.models.SportType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
* @author Shulpov Victor
* @since 1.0
* @version 1.0
*/
@Repository
public interface SportTypeRepo extends JpaRepository<SportType, Integer> {

@Query("FROM SportType WHERE id in :ids")
List<SportType> getByIds(List<Integer> ids);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,19 @@

import com.shulpov.spots_app.spot_references.models.SpotType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
* @author Shulpov Victor
* @since 1.0
* @version 1.0
*/
@Repository
public interface SpotTypeRepo extends JpaRepository<SpotType, Integer> {

@Query("FROM SpotType WHERE id in :ids")
List<SpotType> getByIds(List<Integer> ids);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@
import com.shulpov.spots_app.spot_references.models.SpaceType;
import com.shulpov.spots_app.spot_references.repo.SpaceTypeRepo;
import com.shulpov.spots_app.spot_references.utils.SpaceTypeDtoConverter;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;

/**
Expand All @@ -20,15 +23,11 @@
@Service
@Transactional(readOnly = true)
@Scope(value = "prototype")
@RequiredArgsConstructor
public class SpaceTypeService {
private final SpaceTypeDtoConverter spaceTypeDtoConverter;
private final SpaceTypeRepo spaceTypeRepo;

@Autowired
public SpaceTypeService(SpaceTypeDtoConverter spaceTypeDtoConverter, SpaceTypeRepo spaceTypeRepo) {
this.spaceTypeDtoConverter = spaceTypeDtoConverter;
this.spaceTypeRepo = spaceTypeRepo;
}
private final Logger logger = LoggerFactory.getLogger(SpaceTypeService.class);

/**
* Получить все типы помещений
Expand All @@ -37,6 +36,15 @@ public List<SpaceType> getAll() {
return spaceTypeRepo.findAll();
}

/**
* Получить тип помещения по id
*/
public Optional<SpaceType> getById(Integer id) {
return spaceTypeRepo.findById(id);
}

// DTO ------------------------------------------------------------------------------------

/**
* Получить все типы помещений в виде DTO
*/
Expand All @@ -45,9 +53,15 @@ public List<SpaceTypeDto> getAllDto() {
}

/**
* Получить тип помещения по id
* Получить тип помещения в виде DTO по его id
*/
public Optional<SpaceType> getById(Integer id) {
return spaceTypeRepo.findById(id);
public SpaceTypeDto getDtoById(Integer id) throws NoSuchElementException {
Optional<SpaceType> spaceTypeOpt = getById(id);
if (spaceTypeOpt.isEmpty()) {
logger.error("Space type is not existing: [spot_type_id = '{}']", id);
throw new NoSuchElementException();
} else {
return spaceTypeDtoConverter.convertToDto(spaceTypeOpt.get());
}
}
}
Loading

0 comments on commit ba632f9

Please sign in to comment.