Добавить Setpoint API и репозиторий

This commit is contained in:
Roman Efremov 2024-11-18 09:39:24 +05:00
parent 828864c112
commit d746f85fe4
12 changed files with 198 additions and 25 deletions

View File

@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Mvc;
using Persistence.Models;
using Persistence.Repositories;
namespace Persistence.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class SetpointController : ControllerBase, ISetpointApi
{
private readonly ISetpointRepository setpointRepository;
public SetpointController(ISetpointRepository setpointRepository)
{
this.setpointRepository = setpointRepository;
}
[HttpPost("current")]
public Task<ActionResult<IEnumerable<SetpointValueDto>>> GetCurrentAsync(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
throw new NotImplementedException();
}
[HttpPost("history")]
public async Task<ActionResult<IEnumerable<SetpointValueDto>>> GetHistoryAsync(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
{
var result = await setpointRepository.GetHistoryAsync(setpointKeys, historyMoment, token);
return Ok(result);
}
[HttpPost("log")]
public async Task<ActionResult<Dictionary<Guid, IEnumerable<SetpointLogDto>>>> GetLogAsync([FromBody] IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var result = await setpointRepository.GetLogAsync(setpointKeys, token);
return Ok(result);
}
[HttpPost("save")]
public async Task<ActionResult<int>> SaveAsync(Guid setpointKey, object newValue, CancellationToken token)
{
var result = await setpointRepository.SaveAsync(setpointKey, newValue, token);
return Ok(result);
}
}
}

View File

@ -11,6 +11,7 @@ namespace Persistence.Database.Model;
public interface IPersistenceDbContext : IDisposable public interface IPersistenceDbContext : IDisposable
{ {
DbSet<DataSaub> DataSaub { get; } DbSet<DataSaub> DataSaub { get; }
DbSet<Setpoint> Setpoint { get; }
DatabaseFacade Database { get; } DatabaseFacade Database { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken); Task<int> SaveChangesAsync(CancellationToken cancellationToken);
} }

View File

@ -0,0 +1,10 @@
namespace Persistence.Database.Model
{
public interface ISetpointData
{
public Guid Key { get; set; }
public object Value { get; set; }
public DateTimeOffset Created { get; set; }
public int IdUser { get; set; }
}
}

View File

@ -1,17 +1,16 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
namespace Persistence.Database.Model; namespace Persistence.Database.Model;
public partial class PersistenceDbContext : DbContext, IPersistenceDbContext public partial class PersistenceDbContext : DbContext, IPersistenceDbContext
{ {
public DbSet<DataSaub> DataSaub => Set<DataSaub>(); public DbSet<DataSaub> DataSaub => Set<DataSaub>();
public DbSet<Setpoint> Setpoint => Set<Setpoint>();
public PersistenceDbContext()
{
}
public PersistenceDbContext(DbContextOptions<PersistenceDbContext> options) public PersistenceDbContext(DbContextOptions<PersistenceDbContext> options)
{ {
} }

View File

@ -0,0 +1,22 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Persistence.Database.Model
{
[PrimaryKey(nameof(Key), nameof(Created))]
public class Setpoint : ISetpointData
{
[Comment("Ключ")]
public Guid Key { get; set; }
[Column(TypeName = "jsonb"), Comment("Значение уставки")]
public required object Value { get; set; }
[Comment("Дата изменения уставки")]
public DateTimeOffset Created { get; set; }
[Comment("Id автора последнего изменения")]
public int IdUser { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace Persistence.Database.Model
{
public class SetpointDictionary
{
[Key, Comment("Ключ")]
public Guid Key { get; set; }
[Comment("Наименование")]
public required string Name { get; set; }
[Comment("Описание")]
public string? Description { get; set; }
}
}

View File

@ -0,0 +1,10 @@
namespace Persistence.Repository.Data
{
public class SetpointDto
{
public int Id { get; set; }
public required object Value { get; set; }
public DateTimeOffset Edit { get; set; }
public int IdUser { get; set; }
}
}

View File

@ -21,9 +21,10 @@ public static class DependencyInjection
services.AddDbContext<PersistenceDbContext>(options => services.AddDbContext<PersistenceDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString(connectionStringName))); options.UseNpgsql(configuration.GetConnectionString(connectionStringName)));
services.AddScoped<IPersistenceDbContext>(provider => provider.GetRequiredService<PersistenceDbContext>()); services.AddScoped<DbContext>(provider => provider.GetRequiredService<PersistenceDbContext>());
services.AddTransient<ITimeSeriesDataRepository<DataSaubDto>, TimeSeriesDataRepository<DataSaub, DataSaubDto>>(); services.AddTransient<ITimeSeriesDataRepository<DataSaubDto>, TimeSeriesDataRepository<DataSaub, DataSaubDto>>();
services.AddTransient<ISetpointRepository, SetpointRepository>();
return services; return services;
} }

View File

@ -0,0 +1,70 @@
using Mapster;
using Microsoft.EntityFrameworkCore;
using Persistence.Database.Model;
using Persistence.Models;
using Persistence.Repositories;
namespace Persistence.Repository.Repositories
{
public class SetpointRepository : ISetpointRepository
{
private DbContext db;
public SetpointRepository(DbContext db)
{
this.db = db;
}
protected virtual IQueryable<Setpoint> GetQueryReadOnly() => db.Set<Setpoint>();
public async Task<IEnumerable<SetpointValueDto>> GetHistoryAsync(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query
.Where(e => setpointKeys.Contains(e.Key) && e.Created.Date == historyMoment.Date)
.ToArrayAsync(token);
var dtos = entities.Select(e => e.Adapt<SetpointValueDto>());
return dtos;
}
public async Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLogAsync(IEnumerable<Guid> setpointKeys, CancellationToken token)
{
var query = GetQueryReadOnly();
var entities = await query
.Where(e => setpointKeys.Contains(e.Key))
.ToArrayAsync(token);
var dtos = entities
.GroupBy(e => e.Key)
.Select(e => new KeyValuePair<Guid, IEnumerable<SetpointLogDto>>(
e.Key,
e.Select(s => s.Adapt<SetpointLogDto>())
)).ToDictionary();
return dtos;
}
public async Task<int> SaveAsync(Guid setpointKey, object newValue, CancellationToken token)
{
try
{
var entity = new Setpoint()
{
Key = setpointKey,
Value = newValue,
IdUser = 0, // ToDo: откуда тянуть?
Created = DateTimeOffset.Now.ToUniversalTime()
};
await db.Set<Setpoint>().AddAsync(entity, token);
var result = await db.SaveChangesAsync(token);
return result;
}
catch(Exception ex)
{
var t = ex.Message;
return 0;
}
}
}
}

View File

@ -7,6 +7,6 @@ using System.Threading.Tasks;
namespace Persistence.Models; namespace Persistence.Models;
public class SetpointLogDto : SetpointValueDto public class SetpointLogDto : SetpointValueDto
{ {
public DateTimeOffset Edit { get; set; } public DateTimeOffset Created { get; set; }
public int IdUser { get; set; } public int IdUser { get; set; }
} }

View File

@ -8,7 +8,7 @@ namespace Persistence.Models;
public class SetpointValueDto public class SetpointValueDto
{ {
public int Id { get; set; } public Guid Key { get; set; }
public object Value { get; set; } public required object Value { get; set; }
} }

View File

@ -1,10 +1,4 @@
using Microsoft.AspNetCore.Mvc; using Persistence.Models;
using Persistence.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Persistence.Repositories; namespace Persistence.Repositories;
@ -17,19 +11,19 @@ public interface ISetpointRepository
/// <summary> /// <summary>
/// Получить значения уставок за определенный момент времени /// Получить значения уставок за определенный момент времени
/// </summary> /// </summary>
/// <param name="setpoitKeys"></param> /// <param name="setpointKeys"></param>
/// <param name="historyMoment">дата, на которую получаем данные</param> /// <param name="historyMoment">дата, на которую получаем данные</param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<IEnumerable<SetpointValueDto>> GetHistoryAsync(IEnumerable<Guid> setpoitKeys, DateTimeOffset historyMoment, CancellationToken token); Task<IEnumerable<SetpointValueDto>> GetHistoryAsync(IEnumerable<Guid> setpointKeys, DateTimeOffset historyMoment, CancellationToken token);
/// <summary> /// <summary>
/// Получить историю изменений значений уставок /// Получить историю изменений значений уставок
/// </summary> /// </summary>
/// <param name="setpoitKeys"></param> /// <param name="setpointKeys"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLogAsync(IEnumerable<Guid> setpoitKeys, CancellationToken token); Task<Dictionary<Guid, IEnumerable<SetpointLogDto>>> GetLogAsync(IEnumerable<Guid> setpointKeys, CancellationToken token);
/// <summary> /// <summary>
/// Метод сохранения уставки /// Метод сохранения уставки
@ -41,5 +35,5 @@ public interface ISetpointRepository
/// <returns></returns> /// <returns></returns>
/// to do /// to do
/// id User учесть в соответствующем методе репозитория /// id User учесть в соответствующем методе репозитория
Task<int> SaveAsync(Guid setpointKey, int idUser, object newValue, CancellationToken token); Task<int> SaveAsync(Guid setpointKey, object newValue, CancellationToken token);
} }