我想知道如何验证我的 Rest API 路径 ID 的最佳实践。
例如:
当我执行 GET 检索建筑物时,我需要先验证 {universityId} 和 {campusId} 是否确实有效(存在于数据库中),然后再继续。
现在我已经实现了一个自定义 RepositoryValidation,它通过抛出 ResourceNotFoundException() 来提供这些功能,并且在我的服务类中为 GET、PUT、POST..etc 调用这些方法
有没有更好的方法来进行验证?我已阅读有关拦截器或过滤器的信息,但不确定这是否是最佳做法。
自定义例外:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message) {
super(message);
}
存储库验证:
@Component
public class RepositoryValidation {
@Autowired
private UniversityRepository universityRepository;
@Autowired
private CampusRepository campusRepository;
@Autowired
private BuildingRepository buildingRepository;
public void checkIfUniversityExists(Long universityId){
if (!universityRepository.exists(universityId))
throw new ResourceNotFoundException("University with id: " + universityId + " not found");
}
public void checkIfCampusExists(Long campusId){
if (!campusRepository.exists(campusId))
throw new ResourceNotFoundException("Campus with id: " + campusId + " not found");
}
public void checkIfBuildingExists(Long buildingId){
if (!buildingRepository.exists(buildingId))
throw new ResourceNotFoundException("Building with id: " + buildingId + " not found");
}
}
服务:
@Service
public class BuildingService {
@Autowired
private BuildingRepository buildingRepository;
@Autowired
private RepositoryValidation repositoryValidation;
public Iterable<Building> list(Long campusId) {
return buildingRepository.findAllByCampusId(campusId);
}
@Transactional
public Building create(Building building) {
return buildingRepository.save(building);
}
public Building read(Long buildingId,Long campusId) {
repositoryValidation.checkIfCampusExists(campusId);
repositoryValidation.checkIfBuildingExists(buildingId);
return buildingRepository.findBuildingByIdAndCampusId(buildingId,campusId);
}
@Transactional
public Building update(Long buildingId,Building update) {
repositoryValidation.checkIfBuildingExists(buildingId);
Building building = buildingRepository.findOne(buildingId);
building.setBuildingName(update.getBuildingName());
return buildingRepository.save(building);
}
@Transactional
public void delete(Long buildingId,Long campusId) {
repositoryValidation.checkIfCampusExists(campusId);
repositoryValidation.checkIfBuildingExists(buildingId);
buildingRepository.deleteBuildingByIdAndCampusId(buildingId, campusId);
}