refactor: reorganize Infrastructure layer into folder structure with DI
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
using AutoMapper;
|
||||
using GreenHome.Application;
|
||||
using GreenHome.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GreenHome.Infrastructure.Services.Device;
|
||||
|
||||
public sealed class DeviceSettingsService : IDeviceSettingsService
|
||||
{
|
||||
private readonly GreenHomeDbContext _dbContext;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public DeviceSettingsService(GreenHomeDbContext dbContext, IMapper mapper)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public async Task<DeviceSettingsDto?> GetByDeviceIdAsync(int deviceId, CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = await _dbContext.DeviceSettings
|
||||
.Include(x => x.Device)
|
||||
.AsNoTracking()
|
||||
.FirstOrDefaultAsync(x => x.DeviceId == deviceId, cancellationToken);
|
||||
|
||||
return settings != null ? _mapper.Map<DeviceSettingsDto>(settings) : null;
|
||||
}
|
||||
|
||||
public async Task<int> CreateAsync(DeviceSettingsDto dto, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = _mapper.Map<Domain.DeviceSettings>(dto);
|
||||
entity.CreatedAt = DateTime.UtcNow;
|
||||
entity.UpdatedAt = DateTime.UtcNow;
|
||||
|
||||
_dbContext.DeviceSettings.Add(entity);
|
||||
await _dbContext.SaveChangesAsync(cancellationToken);
|
||||
return entity.Id;
|
||||
}
|
||||
|
||||
public async Task UpdateAsync(DeviceSettingsDto dto, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _dbContext.DeviceSettings
|
||||
.FirstOrDefaultAsync(x => x.DeviceId == dto.DeviceId, cancellationToken);
|
||||
|
||||
if (entity == null)
|
||||
throw new InvalidOperationException($"Device settings not found for device ID {dto.DeviceId}");
|
||||
|
||||
_mapper.Map(dto, entity);
|
||||
entity.UpdatedAt = DateTime.UtcNow;
|
||||
|
||||
await _dbContext.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user