Добавить клиент для работы с записями ChangeLog. Внести правки после ревью

This commit is contained in:
Roman Efremov 2024-12-10 13:55:01 +05:00
parent e21e31aa12
commit b6c75e3816
21 changed files with 360 additions and 230 deletions

View File

@ -3,11 +3,11 @@ using Persistence.Client.Helpers;
using Refit; using Refit;
namespace Persistence.Client.Clients.Base; namespace Persistence.Client.Clients.Base;
public class BaseClient public abstract class BaseClient
{ {
private readonly ILogger logger; private readonly ILogger logger;
public BaseClient(ILogger logger) public BaseClient(ILogger<BaseClient> logger)
{ {
this.logger = logger; this.logger = logger;
} }

View File

@ -0,0 +1,102 @@
using Microsoft.Extensions.Logging;
using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces;
using Persistence.Models;
using Persistence.Models.Requests;
namespace Persistence.Client.Clients;
public class ChangeLogClient : BaseClient, IChangeLogClient
{
private readonly Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient;
public ChangeLogClient(Interfaces.Refit.IRefitChangeLogClient refitChangeLogClient, ILogger<ChangeLogClient> logger) : base(logger)
{
this.refitChangeLogClient = refitChangeLogClient;
}
public async Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
{
var result = await ExecuteGetResponse<int>(
async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token);
return result;
}
public async Task<PaginationContainer<DataWithWellDepthAndSectionDto>> GetByDate(Guid idDiscriminator, DateTimeOffset moment,
SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token)
{
var result = await ExecuteGetResponse<PaginationContainer<DataWithWellDepthAndSectionDto>>(
async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token);
return result;
}
public async Task<IEnumerable<ChangeLogDto>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token)
{
var result = await ExecuteGetResponse<IEnumerable<ChangeLogDto>>(
async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token);
return result;
}
public async Task<int> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitChangeLogClient.Add(idDiscriminator, dto, token), token);
return result;
}
public async Task<int> AddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitChangeLogClient.AddRange(idDiscriminator, dtos, token), token);
return result;
}
public async Task<int> Update(DataWithWellDepthAndSectionDto dto, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitChangeLogClient.Update(dto, token), token);
return result;
}
public async Task<int> UpdateRange(IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitChangeLogClient.UpdateRange(dtos, token), token);
return result;
}
public async Task<int> Delete(Guid id, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitChangeLogClient.Delete(id, token), token);
return result;
}
public async Task<int> DeleteRange(IEnumerable<Guid> ids, CancellationToken token)
{
var result = await ExecutePostResponse(
async () => await refitChangeLogClient.DeleteRange(ids, token), token);
return result;
}
public async Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token)
{
var result = await ExecuteGetResponse<DatesRangeDto?>(
async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token);
return result;
}
public void Dispose()
{
refitChangeLogClient.Dispose();
}
}

View File

@ -1,106 +0,0 @@
using Persistence.Models;
using Persistence.Models.Requests;
using Refit;
namespace Persistence.Client.Clients;
/// <summary>
/// Интерфейс для тестирования API, предназначенного для работы с записями ChangeLod
/// </summary>
public interface IChangeLogClient
{
private const string BaseRoute = "/api/ChangeLog";
/// <summary>
/// Импорт с заменой: удаление старых строк и добавление новых
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dtos"></param>
/// <returns></returns>
[Post($"{BaseRoute}/replace/{{idDiscriminator}}")]
Task<IApiResponse<int>> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos);
/// <summary>
/// Получение актуальных данных на определенную дату (с пагинацией)
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="moment"></param>
/// <param name="filterRequest">параметры запроса фильтрации</param>
/// <param name="paginationRequest">параметры запроса пагинации</param>
/// <returns></returns>
[Get($"{BaseRoute}/moment/{{idDiscriminator}}")]
Task<IApiResponse<PaginationContainer<DataWithWellDepthAndSectionDto>>> GetByDate(
Guid idDiscriminator,
DateTimeOffset moment,
[Query] SectionPartRequest filterRequest,
[Query] PaginationRequest paginationRequest);
/// <summary>
/// Получение исторических данных за определенный период времени
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dateBegin"></param>
/// <param name="dateEnd"></param>
/// <returns></returns>
[Get($"{BaseRoute}/history/{{idDiscriminator}}")]
Task<IApiResponse<IEnumerable<ChangeLogDto>>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd);
/// <summary>
/// Добавить одну запись
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dto"></param>
/// <returns></returns>
[Post($"{BaseRoute}/{{idDiscriminator}}")]
Task<IApiResponse<int>> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto);
/// <summary>
/// Добавить несколько записей
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dtos"></param>
/// <returns></returns>
[Post($"{BaseRoute}/range/{{idDiscriminator}}")]
Task<IApiResponse<int>> AddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos);
/// <summary>
/// Обновить одну запись
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[Put($"{BaseRoute}")]
Task<IApiResponse<int>> Update(DataWithWellDepthAndSectionDto dto);
/// <summary>
/// Обновить несколько записей
/// </summary>
/// <param name="dtos"></param>
/// <returns></returns>
[Put($"{BaseRoute}/range")]
Task<IApiResponse<int>> UpdateRange(IEnumerable<DataWithWellDepthAndSectionDto> dtos);
/// <summary>
/// Удалить одну запись
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Delete($"{BaseRoute}")]
Task<IApiResponse<int>> Delete(Guid id);
/// <summary>
/// Удалить несколько записей
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[Delete($"{BaseRoute}/range")]
Task<IApiResponse<int>> DeleteRange([Body] IEnumerable<Guid> ids);
/// <summary>
/// Получение списка дат, в которые происходили изменения (день, месяц, год, без времени)
/// </summary>
/// <param name="idDiscriminator"></param>
/// <returns></returns>
[Get($"{BaseRoute}/datesRange/{{idDiscriminator}}")]
Task<IApiResponse<DatesRangeDto?>> GetDatesRange(Guid idDiscriminator);
}

View File

@ -0,0 +1,98 @@
using Persistence.Models;
using Persistence.Models.Requests;
namespace Persistence.Client.Clients.Interfaces;
/// <summary>
/// Клиент для работы с записями ChangeLog
/// </summary>
public interface IChangeLogClient : IDisposable
{
/// <summary>
/// Добавить одну запись
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token);
/// <summary>
/// Добавить несколько записей
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> AddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token);
/// <summary>
/// Импорт с заменой: удаление старых строк и добавление новых
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token);
/// <summary>
/// Удалить одну запись
/// </summary>
/// <param name="id"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> Delete(Guid id, CancellationToken token);
/// <summary>
/// Удалить несколько записей
/// </summary>
/// <param name="ids"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> DeleteRange(IEnumerable<Guid> ids, CancellationToken token);
/// <summary>
/// Получение актуальных данных на определенную дату (с пагинацией)
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="moment"></param>
/// <param name="filterRequest"></param>
/// <param name="paginationRequest"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<PaginationContainer<DataWithWellDepthAndSectionDto>> GetByDate(Guid idDiscriminator, DateTimeOffset moment, SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token);
/// <summary>
/// Получение исторических данных за определенный период времени
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="dateBegin"></param>
/// <param name="dateEnd"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<IEnumerable<ChangeLogDto>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token);
/// <summary>
/// Получение списка дат, в которые происходили изменения (день, месяц, год, без времени)
/// </summary>
/// <param name="idDiscriminator"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<DatesRangeDto?> GetDatesRange(Guid idDiscriminator, CancellationToken token);
/// <summary>
/// Обновить одну запись
/// </summary>
/// <param name="dto"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> Update(DataWithWellDepthAndSectionDto dto, CancellationToken token);
/// <summary>
/// Обновить несколько записей
/// </summary>
/// <param name="dtos"></param>
/// <param name="token"></param>
/// <returns></returns>
Task<int> UpdateRange(IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token);
}

View File

@ -5,7 +5,7 @@ namespace Persistence.Client.Clients.Interfaces;
/// <summary> /// <summary>
/// Клиент для работы с уставками /// Клиент для работы с уставками
/// </summary> /// </summary>
public interface ISetpointClient public interface ISetpointClient : IDisposable
{ {
/// <summary> /// <summary>
/// Добавить уставку /// Добавить уставку

View File

@ -1,11 +1,12 @@
using Persistence.Models; using Persistence.Models;
using Persistence.Models.Requests;
namespace Persistence.Client.Clients.Interfaces; namespace Persistence.Client.Clients.Interfaces;
/// <summary> /// <summary>
/// Клиент для работы с технологическими сообщениями /// Клиент для работы с технологическими сообщениями
/// </summary> /// </summary>
public interface ITechMessagesClient public interface ITechMessagesClient : IDisposable
{ {
/// <summary> /// <summary>
/// Добавить новые технологические сообщения /// Добавить новые технологические сообщения
@ -28,7 +29,7 @@ public interface ITechMessagesClient
/// <param name="request"></param> /// <param name="request"></param>
/// <param name="token"></param> /// <param name="token"></param>
/// <returns></returns> /// <returns></returns>
Task<PaginationContainer<TechMessageDto>> GetPage(RequestDto request, CancellationToken token); Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token);
/// <summary> /// <summary>
/// Получить порцию записей, начиная с заданной даты /// Получить порцию записей, начиная с заданной даты

View File

@ -6,7 +6,7 @@ namespace Persistence.Client.Clients.Interfaces;
/// Клиент для работы с временными данными /// Клиент для работы с временными данными
/// </summary> /// </summary>
/// <typeparam name="TDto"></typeparam> /// <typeparam name="TDto"></typeparam>
public interface ITimeSeriesClient<TDto> where TDto : class, new() public interface ITimeSeriesClient<TDto> : IDisposable where TDto : class, new()
{ {
/// <summary> /// <summary>
/// Добавление записей /// Добавление записей

View File

@ -3,9 +3,12 @@
namespace Persistence.Client.Clients.Interfaces; namespace Persistence.Client.Clients.Interfaces;
/// <summary> /// <summary>
/// Клиент для работы с данными с отметкой времени /// Клиент для работы с репозиторием для хранения разных наборов данных рядов.
/// idDiscriminator - идентифицирует конкретный набор данных, прим.: циклы измерения АСИБР, или отчет о DrillTest.
/// idDiscriminator формируют клиенты и только им известно что они обозначают.
/// Так как данные приходят редко, то их прореживания для построения графиков не предусмотрено.
/// </summary> /// </summary>
public interface ITimestampedSetClient public interface ITimestampedSetClient : IDisposable
{ {
/// <summary> /// <summary>
/// Записать новые данные /// Записать новые данные

View File

@ -0,0 +1,46 @@
using Persistence.Models;
using Persistence.Models.Requests;
using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitChangeLogClient : IDisposable
{
private const string BaseRoute = "/api/ChangeLog";
[Post($"{BaseRoute}/replace/{{idDiscriminator}}")]
Task<IApiResponse<int>> ClearAndAddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token);
[Get($"{BaseRoute}/moment/{{idDiscriminator}}")]
Task<IApiResponse<PaginationContainer<DataWithWellDepthAndSectionDto>>> GetByDate(
Guid idDiscriminator,
DateTimeOffset moment,
[Query] SectionPartRequest filterRequest,
[Query] PaginationRequest paginationRequest,
CancellationToken token);
[Get($"{BaseRoute}/history/{{idDiscriminator}}")]
Task<IApiResponse<IEnumerable<ChangeLogDto>>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token);
[Post($"{BaseRoute}/{{idDiscriminator}}")]
Task<IApiResponse<int>> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token);
[Post($"{BaseRoute}/range/{{idDiscriminator}}")]
Task<IApiResponse<int>> AddRange(Guid idDiscriminator, IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token);
[Put($"{BaseRoute}")]
Task<IApiResponse<int>> Update(DataWithWellDepthAndSectionDto dto, CancellationToken token);
[Put($"{BaseRoute}/range")]
Task<IApiResponse<int>> UpdateRange(IEnumerable<DataWithWellDepthAndSectionDto> dtos, CancellationToken token);
[Delete($"{BaseRoute}")]
Task<IApiResponse<int>> Delete(Guid id, CancellationToken token);
[Delete($"{BaseRoute}/range")]
Task<IApiResponse<int>> DeleteRange([Body] IEnumerable<Guid> ids, CancellationToken token);
[Get($"{BaseRoute}/datesRange/{{idDiscriminator}}")]
Task<IApiResponse<DatesRangeDto?>> GetDatesRange(Guid idDiscriminator, CancellationToken token);
}

View File

@ -3,10 +3,7 @@ using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit; namespace Persistence.Client.Clients.Interfaces.Refit;
/// <summary> public interface IRefitSetpointClient : IDisposable
/// Интерфейс клиента для работы с уставками
/// </summary>
public interface IRefitSetpointClient
{ {
private const string BaseRoute = "/api/setpoint"; private const string BaseRoute = "/api/setpoint";

View File

@ -1,17 +1,15 @@
using Persistence.Models; using Persistence.Models;
using Persistence.Models.Requests;
using Refit; using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit namespace Persistence.Client.Clients.Interfaces.Refit
{ {
/// <summary> public interface IRefitTechMessagesClient : IDisposable
/// Интерфейс клиента для хранения технологических сообщений
/// </summary>
public interface IRefitTechMessagesClient
{ {
private const string BaseRoute = "/api/techMessages"; private const string BaseRoute = "/api/techMessages";
[Get($"{BaseRoute}")] [Get($"{BaseRoute}")]
Task<IApiResponse<PaginationContainer<TechMessageDto>>> GetPage([Query] RequestDto request, CancellationToken token); Task<IApiResponse<PaginationContainer<TechMessageDto>>> GetPage([Query] PaginationRequest request, CancellationToken token);
[Post($"{BaseRoute}")] [Post($"{BaseRoute}")]
Task<IApiResponse<int>> AddRange([Body] IEnumerable<TechMessageDto> dtos, CancellationToken token); Task<IApiResponse<int>> AddRange([Body] IEnumerable<TechMessageDto> dtos, CancellationToken token);

View File

@ -2,8 +2,8 @@
using Refit; using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit; namespace Persistence.Client.Clients.Interfaces.Refit;
public interface IRefitTimeSeriesClient<TDto> public interface IRefitTimeSeriesClient<TDto> : IDisposable
where TDto : class, new() where TDto : class, new()
{ {
private const string BaseRoute = "/api/dataSaub"; private const string BaseRoute = "/api/dataSaub";

View File

@ -3,60 +3,22 @@ using Refit;
namespace Persistence.Client.Clients.Interfaces.Refit; namespace Persistence.Client.Clients.Interfaces.Refit;
/// <summary> public interface IRefitTimestampedSetClient : IDisposable
/// Клиент для работы с репозиторием для хранения разных наборов данных рядов.
/// idDiscriminator - идентифицирует конкретный набор данных, прим.: циклы измерения АСИБР, или отчет о DrillTest.
/// idDiscriminator формируют клиенты и только им известно что они обозначают.
/// Так как данные приходят редко, то их прореживания для построения графиков не предусмотрено.
/// </summary>
public interface IRefitTimestampedSetClient
{ {
private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}"; private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}";
/// <summary>
/// Добавление новых данных
/// </summary>
/// <param name="idDiscriminator">Дискриминатор (идентификатор) набора</param>
/// <param name="sets"></param>
/// <returns></returns>
[Post(baseUrl)] [Post(baseUrl)]
Task<IApiResponse<int>> AddRange(Guid idDiscriminator, IEnumerable<TimestampedSetDto> sets, CancellationToken token); Task<IApiResponse<int>> AddRange(Guid idDiscriminator, IEnumerable<TimestampedSetDto> sets, CancellationToken token);
/// <summary>
/// Получение данных с фильтрацией. Значение фильтра null - отключен
/// </summary>
/// <param name="idDiscriminator">Дискриминатор (идентификатор) набора</param>
/// <param name="geTimestamp">Фильтр позднее даты</param>
/// <param name="columnNames">Фильтр свойств набора. Можно запросить только некоторые свойства из набора</param>
/// <param name="skip"></param>
/// <param name="take"></param>
/// <returns></returns>
[Get(baseUrl)] [Get(baseUrl)]
Task<IApiResponse<IEnumerable<TimestampedSetDto>>> Get(Guid idDiscriminator, [Query] DateTimeOffset? geTimestamp, [Query] IEnumerable<string>? columnNames, int skip, int take, CancellationToken token); Task<IApiResponse<IEnumerable<TimestampedSetDto>>> Get(Guid idDiscriminator, [Query] DateTimeOffset? geTimestamp, [Query] IEnumerable<string>? columnNames, int skip, int take, CancellationToken token);
/// <summary>
/// Получить последние данные
/// </summary>
/// <param name="idDiscriminator">Дискриминатор (идентификатор) набора</param>
/// <param name="columnNames">Фильтр свойств набора. Можно запросить только некоторые свойства из набора</param>
/// <param name="take"></param>
/// <returns></returns>
[Get($"{baseUrl}/last")] [Get($"{baseUrl}/last")]
Task<IApiResponse<IEnumerable<TimestampedSetDto>>> GetLast(Guid idDiscriminator, [Query] IEnumerable<string>? columnNames, int take, CancellationToken token); Task<IApiResponse<IEnumerable<TimestampedSetDto>>> GetLast(Guid idDiscriminator, [Query] IEnumerable<string>? columnNames, int take, CancellationToken token);
/// <summary>
/// Количество записей по указанному набору в БД. Для пагинации.
/// </summary>
/// <param name="idDiscriminator">Дискриминатор (идентификатор) набора</param>
/// <returns></returns>
[Get($"{baseUrl}/count")] [Get($"{baseUrl}/count")]
Task<IApiResponse<int>> Count(Guid idDiscriminator, CancellationToken token); Task<IApiResponse<int>> Count(Guid idDiscriminator, CancellationToken token);
/// <summary>
/// Диапазон дат за которые есть данные
/// </summary>
/// <param name="idDiscriminator">Дискриминатор (идентификатор) набора</param>
/// <returns></returns>
[Get($"{baseUrl}/datesRange")] [Get($"{baseUrl}/datesRange")]
Task<IApiResponse<DatesRangeDto?>> GetDatesRange(Guid idDiscriminator, CancellationToken token); Task<IApiResponse<DatesRangeDto?>> GetDatesRange(Guid idDiscriminator, CancellationToken token);
} }

View File

@ -10,7 +10,7 @@ public class SetpointClient : BaseClient, ISetpointClient
{ {
private readonly IRefitSetpointClient refitSetpointClient; private readonly IRefitSetpointClient refitSetpointClient;
public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger logger) : base(logger) public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger<SetpointClient> logger) : base(logger)
{ {
this.refitSetpointClient = refitSetpointClient; this.refitSetpointClient = refitSetpointClient;
} }
@ -60,4 +60,9 @@ public class SetpointClient : BaseClient, ISetpointClient
await ExecutePostResponse( await ExecutePostResponse(
async () => await refitSetpointClient.Add(setpointKey, newValue, token), token); async () => await refitSetpointClient.Add(setpointKey, newValue, token), token);
} }
public void Dispose()
{
refitSetpointClient.Dispose();
}
} }

View File

@ -3,6 +3,7 @@ using Persistence.Client.Clients.Base;
using Persistence.Client.Clients.Interfaces; using Persistence.Client.Clients.Interfaces;
using Persistence.Client.Clients.Interfaces.Refit; using Persistence.Client.Clients.Interfaces.Refit;
using Persistence.Models; using Persistence.Models;
using Persistence.Models.Requests;
namespace Persistence.Client.Clients; namespace Persistence.Client.Clients;
@ -10,12 +11,12 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
{ {
private readonly IRefitTechMessagesClient refitTechMessagesClient; private readonly IRefitTechMessagesClient refitTechMessagesClient;
public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger logger) : base(logger) public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger<TechMessagesClient> logger) : base(logger)
{ {
this.refitTechMessagesClient = refitTechMessagesClient; this.refitTechMessagesClient = refitTechMessagesClient;
} }
public async Task<PaginationContainer<TechMessageDto>> GetPage(RequestDto request, CancellationToken token) public async Task<PaginationContainer<TechMessageDto>> GetPage(PaginationRequest request, CancellationToken token)
{ {
var result = await ExecuteGetResponse<PaginationContainer<TechMessageDto>>( var result = await ExecuteGetResponse<PaginationContainer<TechMessageDto>>(
async () => await refitTechMessagesClient.GetPage(request, token), token); async () => await refitTechMessagesClient.GetPage(request, token), token);
@ -62,4 +63,9 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
return result; return result;
} }
public void Dispose()
{
refitTechMessagesClient.Dispose();
}
} }

View File

@ -9,7 +9,7 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
{ {
private readonly IRefitTimeSeriesClient<TDto> timeSeriesClient; private readonly IRefitTimeSeriesClient<TDto> timeSeriesClient;
public TimeSeriesClient(IRefitTimeSeriesClient<TDto> refitTechMessagesClient, ILogger logger) : base(logger) public TimeSeriesClient(IRefitTimeSeriesClient<TDto> refitTechMessagesClient, ILogger<TimeSeriesClient<TDto>> logger) : base(logger)
{ {
this.timeSeriesClient = refitTechMessagesClient; this.timeSeriesClient = refitTechMessagesClient;
} }
@ -45,4 +45,9 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
return result; return result;
} }
public void Dispose()
{
timeSeriesClient.Dispose();
}
} }

View File

@ -9,7 +9,7 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
{ {
private readonly IRefitTimestampedSetClient refitTimestampedSetClient; private readonly IRefitTimestampedSetClient refitTimestampedSetClient;
public TimestampedSetClient(IRefitTimestampedSetClient refitTimestampedSetClient, ILogger logger) : base(logger) public TimestampedSetClient(IRefitTimestampedSetClient refitTimestampedSetClient, ILogger<TimestampedSetClient> logger) : base(logger)
{ {
this.refitTimestampedSetClient = refitTimestampedSetClient; this.refitTimestampedSetClient = refitTimestampedSetClient;
} }
@ -53,4 +53,9 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient
return result; return result;
} }
public void Dispose()
{
refitTimestampedSetClient.Dispose();
}
} }

View File

@ -7,6 +7,7 @@ using Refit;
using Persistence.Factories; using Persistence.Factories;
using Persistence.Client.Clients.Interfaces.Refit; using Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
namespace Persistence.Client namespace Persistence.Client
{ {
@ -21,20 +22,20 @@ namespace Persistence.Client
PropertyNameCaseInsensitive = true PropertyNameCaseInsensitive = true
}; };
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions)); private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly ILogger logger; private readonly IServiceProvider provider;
private HttpClient httpClient; private HttpClient httpClient;
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, ILogger<PersistenceClientFactory> logger, IConfiguration configuration) public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IServiceProvider provider, IConfiguration configuration)
{ {
this.logger = logger; this.provider = provider;
httpClient = httpClientFactory.CreateClient(); httpClient = httpClientFactory.CreateClient();
httpClient.Authorize(configuration); httpClient.Authorize(configuration);
} }
public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IAuthTokenFactory authTokenFactory, ILogger logger, IConfiguration configuration) public PersistenceClientFactory(IHttpClientFactory httpClientFactory, IAuthTokenFactory authTokenFactory, IServiceProvider provider, IConfiguration configuration)
{ {
this.logger = logger; this.provider = provider;
httpClient = httpClientFactory.CreateClient(); httpClient = httpClientFactory.CreateClient();
@ -48,6 +49,8 @@ namespace Persistence.Client
/// <returns></returns> /// <returns></returns>
public ISetpointClient GetSetpointClient() public ISetpointClient GetSetpointClient()
{ {
var logger = provider.GetRequiredService<ILogger<SetpointClient>>();
var restClient = RestService.For<IRefitSetpointClient>(httpClient, RefitSettings); var restClient = RestService.For<IRefitSetpointClient>(httpClient, RefitSettings);
var client = new SetpointClient(restClient, logger); var client = new SetpointClient(restClient, logger);
@ -60,6 +63,8 @@ namespace Persistence.Client
/// <returns></returns> /// <returns></returns>
public ITechMessagesClient GetTechMessagesClient() public ITechMessagesClient GetTechMessagesClient()
{ {
var logger = provider.GetRequiredService<ILogger<TechMessagesClient>>();
var restClient = RestService.For<IRefitTechMessagesClient>(httpClient, RefitSettings); var restClient = RestService.For<IRefitTechMessagesClient>(httpClient, RefitSettings);
var client = new TechMessagesClient(restClient, logger); var client = new TechMessagesClient(restClient, logger);
@ -74,6 +79,8 @@ namespace Persistence.Client
public ITimeSeriesClient<TDto> GetTimeSeriesClient<TDto>() public ITimeSeriesClient<TDto> GetTimeSeriesClient<TDto>()
where TDto : class, new() where TDto : class, new()
{ {
var logger = provider.GetRequiredService<ILogger<TimeSeriesClient<TDto>>>();
var restClient = RestService.For<IRefitTimeSeriesClient<TDto>>(httpClient, RefitSettings); var restClient = RestService.For<IRefitTimeSeriesClient<TDto>>(httpClient, RefitSettings);
var client = new TimeSeriesClient<TDto>(restClient, logger); var client = new TimeSeriesClient<TDto>(restClient, logger);
@ -86,10 +93,26 @@ namespace Persistence.Client
/// <returns></returns> /// <returns></returns>
public ITimestampedSetClient GetTimestampedSetClient() public ITimestampedSetClient GetTimestampedSetClient()
{ {
var logger = provider.GetRequiredService<ILogger<TimestampedSetClient>>();
var restClient = RestService.For<IRefitTimestampedSetClient>(httpClient, RefitSettings); var restClient = RestService.For<IRefitTimestampedSetClient>(httpClient, RefitSettings);
var client = new TimestampedSetClient(restClient, logger); var client = new TimestampedSetClient(restClient, logger);
return client; return client;
} }
/// <summary>
/// Получить клиент для работы с записями ChangeLog
/// </summary>
/// <returns></returns>
public IChangeLogClient GetChangeLogClient()
{
var logger = provider.GetRequiredService<ILogger<ChangeLogClient>>();
var restClient = RestService.For<IRefitChangeLogClient>(httpClient, RefitSettings);
var client = new ChangeLogClient(restClient, logger);
return client;
}
} }
} }

View File

@ -13,6 +13,7 @@ Persistence сервисом посредством обращения к кон
- `ITechMessagesClient` - Клиент для работы с технологическими сообщениями - `ITechMessagesClient` - Клиент для работы с технологическими сообщениями
- `ITimeSeriesClient` - Клиент для работы с временными данными - `ITimeSeriesClient` - Клиент для работы с временными данными
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени - `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
## Использование ## Использование
Для получения того или иного Persistence - клиента нужно Для получения того или иного Persistence - клиента нужно

View File

@ -2,11 +2,10 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Persistence.Client; using Persistence.Client;
using Persistence.Client.Clients; using Persistence.Client.Clients.Interfaces;
using Persistence.Database.Model; using Persistence.Database.Model;
using Persistence.Models; using Persistence.Models;
using Persistence.Models.Requests; using Persistence.Models.Requests;
using System.Net;
using Xunit; using Xunit;
namespace Persistence.IntegrationTests.Controllers; namespace Persistence.IntegrationTests.Controllers;
@ -20,7 +19,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var persistenceClientFactory = scope.ServiceProvider var persistenceClientFactory = scope.ServiceProvider
.GetRequiredService<PersistenceClientFactory>(); .GetRequiredService<PersistenceClientFactory>();
client = persistenceClientFactory.GetClient<IChangeLogClient>(); client = persistenceClientFactory.GetChangeLogClient();
} }
[Fact] [Fact]
@ -31,11 +30,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var dtos = Generate(2, DateTimeOffset.UtcNow); var dtos = Generate(2, DateTimeOffset.UtcNow);
// act // act
var result = await client.ClearAndAddRange(idDiscriminator, dtos); var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(2, result);
Assert.Equal(2, result.Content);
} }
[Fact] [Fact]
@ -48,11 +46,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var dtos = createdResult.Item2.Select(e => e.Adapt<DataWithWellDepthAndSectionDto>()); var dtos = createdResult.Item2.Select(e => e.Adapt<DataWithWellDepthAndSectionDto>());
// act // act
var result = await client.ClearAndAddRange(idDiscriminator, dtos); var result = await client.ClearAndAddRange(idDiscriminator, dtos, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(insertedCount*2, result);
Assert.Equal(insertedCount*2, result.Content);
} }
[Fact] [Fact]
@ -65,11 +62,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var dto = dtos.FirstOrDefault()!; var dto = dtos.FirstOrDefault()!;
// act // act
var result = await client.Add(idDiscriminator, dto); var result = await client.Add(idDiscriminator, dto, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.Created, result.StatusCode); Assert.Equal(count, result);
Assert.Equal(count, result.Content);
} }
[Fact] [Fact]
@ -81,11 +77,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var dtos = Generate(count, DateTimeOffset.UtcNow); var dtos = Generate(count, DateTimeOffset.UtcNow);
// act // act
var result = await client.AddRange(idDiscriminator, dtos); var result = await client.AddRange(idDiscriminator, dtos, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.Created, result.StatusCode); Assert.Equal(count, result);
Assert.Equal(count, result.Content);
} }
[Fact] [Fact]
@ -95,8 +90,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var idDiscriminator = Guid.NewGuid(); var idDiscriminator = Guid.NewGuid();
var dtos = Generate(1, DateTimeOffset.UtcNow); var dtos = Generate(1, DateTimeOffset.UtcNow);
var dto = dtos.FirstOrDefault()!; var dto = dtos.FirstOrDefault()!;
var result = await client.Add(idDiscriminator, dto); var result = await client.Add(idDiscriminator, dto, new CancellationToken());
Assert.Equal(HttpStatusCode.Created, result.StatusCode);
var entity = dbContext.ChangeLog var entity = dbContext.ChangeLog
.Where(x => x.IdDiscriminator == idDiscriminator) .Where(x => x.IdDiscriminator == idDiscriminator)
@ -105,27 +99,23 @@ public class ChangeLogControllerTest : BaseIntegrationTest
dto.DepthEnd = dto.DepthEnd + 10; dto.DepthEnd = dto.DepthEnd + 10;
// act // act
result = await client.Update(dto); result = await client.Update(dto, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(2, result);
Assert.Equal(2, result.Content);
var dateBegin = DateTimeOffset.UtcNow.AddDays(-1); var dateBegin = DateTimeOffset.UtcNow.AddDays(-1);
var dateEnd = DateTimeOffset.UtcNow.AddDays(1); var dateEnd = DateTimeOffset.UtcNow.AddDays(1);
var changeLogResult = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd); var changeLogResult = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, new CancellationToken());
Assert.Equal(HttpStatusCode.OK, changeLogResult.StatusCode); Assert.NotNull(changeLogResult);
Assert.NotNull(changeLogResult.Content);
var changeLogDtos = changeLogResult.Content; var obsoleteDto = changeLogResult
.Where(e => e.Obsolete.HasValue)
var obsoleteDto = changeLogDtos
.Where(e => e.Obsolete.HasValue)
.FirstOrDefault(); .FirstOrDefault();
var activeDto = changeLogDtos var activeDto = changeLogResult
.Where(e => !e.Obsolete.HasValue) .Where(e => !e.Obsolete.HasValue)
.FirstOrDefault(); .FirstOrDefault();
if (obsoleteDto == null || activeDto == null) if (obsoleteDto == null || activeDto == null)
@ -158,11 +148,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
}).ToArray(); }).ToArray();
// act // act
var result = await client.UpdateRange(dtos); var result = await client.UpdateRange(dtos, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(count * 2, result);
Assert.Equal(count * 2, result.Content);
} }
[Fact] [Fact]
@ -176,11 +165,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
dbContext.SaveChanges(); dbContext.SaveChanges();
// act // act
var result = await client.Delete(entity.Id); var result = await client.Delete(entity.Id, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(1, result);
Assert.Equal(1, result.Content);
} }
[Fact] [Fact]
@ -195,11 +183,10 @@ public class ChangeLogControllerTest : BaseIntegrationTest
// act // act
var ids = entities.Select(e => e.Id); var ids = entities.Select(e => e.Id);
var result = await client.DeleteRange(ids); var result = await client.DeleteRange(ids, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.Equal(count, result);
Assert.Equal(count, result.Content);
} }
[Fact] [Fact]
@ -211,21 +198,20 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var entities = changeLogItems.Item2.OrderBy(e => e.Creation); var entities = changeLogItems.Item2.OrderBy(e => e.Creation);
// act // act
var result = await client.GetDatesRange(idDiscriminator); var result = await client.GetDatesRange(idDiscriminator, new CancellationToken());
// assert // assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.NotNull(result);
Assert.NotNull(result.Content);
var minDate = entities.First().Creation; var minDate = entities.First().Creation;
var maxDate = entities.Last().Creation; var maxDate = entities.Last().Creation;
var expectedMinDate = minDate.ToUniversalTime().ToString(); var expectedMinDate = minDate.ToUniversalTime().ToString();
var actualMinDate = result.Content.From.ToUniversalTime().ToString(); var actualMinDate = result.From.ToUniversalTime().ToString();
Assert.Equal(expectedMinDate, actualMinDate); Assert.Equal(expectedMinDate, actualMinDate);
var expectedMaxDate = maxDate.ToUniversalTime().ToString(); var expectedMaxDate = maxDate.ToUniversalTime().ToString();
var actualMaxDate = result.Content.To.ToUniversalTime().ToString(); var actualMaxDate = result.To.ToUniversalTime().ToString();
Assert.Equal(expectedMaxDate, actualMaxDate); Assert.Equal(expectedMaxDate, actualMaxDate);
} }
@ -244,7 +230,7 @@ public class ChangeLogControllerTest : BaseIntegrationTest
var ids = entities.Select(e => e.Id); var ids = entities.Select(e => e.Id);
var idsToDelete = ids.Skip(2); var idsToDelete = ids.Skip(2);
var deletedCount = await client.DeleteRange(idsToDelete); var deletedCount = await client.DeleteRange(idsToDelete, new CancellationToken());
var filterRequest = new SectionPartRequest() var filterRequest = new SectionPartRequest()
{ {
@ -260,16 +246,15 @@ public class ChangeLogControllerTest : BaseIntegrationTest
}; };
var moment = DateTimeOffset.UtcNow.AddDays(16); var moment = DateTimeOffset.UtcNow.AddDays(16);
var result = await client.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest); var result = await client.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, new CancellationToken());
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.NotNull(result);
Assert.NotNull(result.Content);
var restEntities = entities.Where(e => !idsToDelete.Contains(e.Id)); var restEntities = entities.Where(e => !idsToDelete.Contains(e.Id));
Assert.Equal(restEntities.Count(), result.Content.Count); Assert.Equal(restEntities.Count(), result.Count);
var actualIds = restEntities.Select(e => e.Id); var actualIds = restEntities.Select(e => e.Id);
var expectedIds = result.Content.Items.Select(e => e.Id); var expectedIds = result.Items.Select(e => e.Id);
Assert.Equivalent(expectedIds, actualIds); Assert.Equivalent(expectedIds, actualIds);
} }
@ -297,17 +282,16 @@ public class ChangeLogControllerTest : BaseIntegrationTest
entity.DepthEnd = entity.DepthEnd + 10; entity.DepthEnd = entity.DepthEnd + 10;
} }
var dtos = entities.Select(e => e.Adapt<DataWithWellDepthAndSectionDto>()).ToArray(); var dtos = entities.Select(e => e.Adapt<DataWithWellDepthAndSectionDto>()).ToArray();
await client.UpdateRange(dtos); await client.UpdateRange(dtos, new CancellationToken());
//act //act
var dateBegin = DateTimeOffset.UtcNow.AddDays(daysBeforeNowFilter); var dateBegin = DateTimeOffset.UtcNow.AddDays(daysBeforeNowFilter);
var dateEnd = DateTimeOffset.UtcNow.AddDays(daysAfterNowFilter); var dateEnd = DateTimeOffset.UtcNow.AddDays(daysAfterNowFilter);
var result = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd); var result = await client.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, new CancellationToken());
//assert //assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode); Assert.NotNull(result);
Assert.NotNull(result.Content); Assert.Equal(changeLogCount, result.Count());
Assert.Equal(changeLogCount, result.Content.Count());
} }

View File

@ -32,7 +32,7 @@ namespace Persistence.IntegrationTests.Controllers
dbContext.CleanupDbSet<TechMessage>(); dbContext.CleanupDbSet<TechMessage>();
dbContext.CleanupDbSet<Database.Entity.DrillingSystem>(); dbContext.CleanupDbSet<Database.Entity.DrillingSystem>();
var PaginationRequest = new PaginationRequest() var requestDto = new PaginationRequest()
{ {
Skip = 1, Skip = 1,
Take = 2, Take = 2,
@ -40,7 +40,7 @@ namespace Persistence.IntegrationTests.Controllers
}; };
//act //act
var response = await techMessagesClient.GetPage(PaginationRequest, new CancellationToken()); var response = await techMessagesClient.GetPage(requestDto, new CancellationToken());
//assert //assert
Assert.NotNull(response); Assert.NotNull(response);