删除设备时检查
This commit is contained in:
		@@ -3,6 +3,7 @@ package service
 | 
			
		||||
import (
 | 
			
		||||
	"encoding/json"
 | 
			
		||||
	"errors"
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"strconv"
 | 
			
		||||
 | 
			
		||||
	"git.huangwc.com/pig/pig-farm-controller/internal/app/dto"
 | 
			
		||||
@@ -11,6 +12,9 @@ import (
 | 
			
		||||
	"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
// ErrDeviceInUse 表示设备正在被任务使用,无法删除
 | 
			
		||||
var ErrDeviceInUse = errors.New("设备正在被一个或多个任务使用,无法删除")
 | 
			
		||||
 | 
			
		||||
// DeviceService 定义了应用层的设备服务接口,用于协调设备相关的业务逻辑。
 | 
			
		||||
type DeviceService interface {
 | 
			
		||||
	CreateDevice(req *dto.CreateDeviceRequest) (*dto.DeviceResponse, error)
 | 
			
		||||
@@ -142,14 +146,27 @@ func (s *deviceService) DeleteDevice(id string) error {
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		return err
 | 
			
		||||
	}
 | 
			
		||||
	deviceID := uint(idUint)
 | 
			
		||||
 | 
			
		||||
	// Check if device exists before deleting
 | 
			
		||||
	_, err = s.deviceRepo.FindByID(uint(idUint))
 | 
			
		||||
	// 检查设备是否存在
 | 
			
		||||
	_, err = s.deviceRepo.FindByID(deviceID)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		return err
 | 
			
		||||
		return err // 如果未找到,会返回 gorm.ErrRecordNotFound
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return s.deviceRepo.Delete(uint(idUint))
 | 
			
		||||
	// 在删除前检查设备是否被任务使用
 | 
			
		||||
	inUse, err := s.deviceRepo.IsDeviceInUse(deviceID)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		// 如果检查过程中发生数据库错误,则返回错误
 | 
			
		||||
		return fmt.Errorf("检查设备使用情况失败: %w", err)
 | 
			
		||||
	}
 | 
			
		||||
	if inUse {
 | 
			
		||||
		// 如果设备正在被使用,则返回特定的业务错误
 | 
			
		||||
		return ErrDeviceInUse
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// 只有在未被使用时,才执行删除操作
 | 
			
		||||
	return s.deviceRepo.Delete(deviceID)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *deviceService) ManualControl(id string, req *dto.ManualControlDeviceRequest) error {
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user