using AutoMapper;
using DMS.Application.DTOs;
using DMS.Application.Interfaces;
using DMS.Application.Interfaces.Database;
using DMS.Core.Interfaces;
using DMS.Core.Models;
namespace DMS.Application.Services.Database;
///
/// MQTT应用服务,负责处理MQTT服务器相关的业务逻辑。
/// 实现 接口。
///
public class MqttAppService : IMqttAppService
{
private readonly IRepositoryManager _repoManager;
private readonly IMapper _mapper;
///
/// 构造函数,通过依赖注入获取仓储管理器和AutoMapper实例。
///
/// 仓储管理器实例。
/// AutoMapper 实例。
public MqttAppService(IRepositoryManager repoManager, IMapper mapper)
{
_repoManager = repoManager;
_mapper = mapper;
}
///
/// 异步根据ID获取MQTT服务器数据传输对象。
///
/// MQTT服务器ID。
/// MQTT服务器数据传输对象。
public async Task GetMqttServerByIdAsync(int id)
{
var mqttServer = await _repoManager.MqttServers.GetByIdAsync(id);
return _mapper.Map(mqttServer);
}
///
/// 异步获取所有MQTT服务器数据传输对象列表。
///
/// MQTT服务器数据传输对象列表。
public async Task> GetAllMqttServersAsync()
{
var mqttServers = await _repoManager.MqttServers.GetAllAsync();
return _mapper.Map>(mqttServers);
}
///
/// 异步创建一个新MQTT服务器(事务性操作)。
///
/// 要创建的MQTT服务器数据传输对象。
/// 新创建MQTT服务器的ID。
/// 如果创建MQTT服务器时发生错误。
public async Task CreateMqttServerAsync(MqttServerDto mqttServerDto)
{
try
{
await _repoManager.BeginTranAsync();
var mqttServer = _mapper.Map(mqttServerDto);
await _repoManager.MqttServers.AddAsync(mqttServer);
await _repoManager.CommitAsync();
return mqttServer.Id;
}
catch (Exception ex)
{
await _repoManager.RollbackAsync();
throw new ApplicationException("创建MQTT服务器时发生错误,操作已回滚。", ex);
}
}
///
/// 异步更新一个已存在的MQTT服务器(事务性操作)。
///
/// 要更新的MQTT服务器数据传输对象。
/// 表示异步操作的任务。
/// 如果找不到MQTT服务器或更新MQTT服务器时发生错误。
public async Task UpdateMqttServerAsync(MqttServerDto mqttServerDto)
{
try
{
await _repoManager.BeginTranAsync();
var mqttServer = await _repoManager.MqttServers.GetByIdAsync(mqttServerDto.Id);
if (mqttServer == null)
{
throw new ApplicationException($"MQTT Server with ID {mqttServerDto.Id} not found.");
}
_mapper.Map(mqttServerDto, mqttServer);
await _repoManager.MqttServers.UpdateAsync(mqttServer);
await _repoManager.CommitAsync();
}
catch (Exception ex)
{
await _repoManager.RollbackAsync();
throw new ApplicationException("更新MQTT服务器时发生错误,操作已回滚。", ex);
}
}
///
/// 异步根据ID删除一个MQTT服务器(事务性操作)。
///
/// 要删除MQTT服务器的ID。
/// 如果删除成功则为 true,否则为 false。
/// 如果删除MQTT服务器时发生错误。
public async Task DeleteMqttServerAsync(int id)
{
try
{
return await _repoManager.MqttServers.DeleteByIdAsync(id);
}
catch (Exception ex)
{
await _repoManager.RollbackAsync();
throw new ApplicationException($"删除MQTT服务器时发生错误,操作已回滚,错误信息:{ex.Message}", ex);
}
}
}