Добавить клиент для работы с записями 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;
namespace Persistence.Client.Clients.Base;
public class BaseClient
public abstract class BaseClient
{
private readonly ILogger logger;
public BaseClient(ILogger logger)
public BaseClient(ILogger<BaseClient> 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>
public interface ISetpointClient
public interface ISetpointClient : IDisposable
{
/// <summary>
/// Добавить уставку

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ public class SetpointClient : BaseClient, ISetpointClient
{
private readonly IRefitSetpointClient refitSetpointClient;
public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger logger) : base(logger)
public SetpointClient(IRefitSetpointClient refitSetpointClient, ILogger<SetpointClient> logger) : base(logger)
{
this.refitSetpointClient = refitSetpointClient;
}
@ -60,4 +60,9 @@ public class SetpointClient : BaseClient, ISetpointClient
await ExecutePostResponse(
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.Refit;
using Persistence.Models;
using Persistence.Models.Requests;
namespace Persistence.Client.Clients;
@ -10,12 +11,12 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
{
private readonly IRefitTechMessagesClient refitTechMessagesClient;
public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger logger) : base(logger)
public TechMessagesClient(IRefitTechMessagesClient refitTechMessagesClient, ILogger<TechMessagesClient> logger) : base(logger)
{
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>>(
async () => await refitTechMessagesClient.GetPage(request, token), token);
@ -62,4 +63,9 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient
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;
public TimeSeriesClient(IRefitTimeSeriesClient<TDto> refitTechMessagesClient, ILogger logger) : base(logger)
public TimeSeriesClient(IRefitTimeSeriesClient<TDto> refitTechMessagesClient, ILogger<TimeSeriesClient<TDto>> logger) : base(logger)
{
this.timeSeriesClient = refitTechMessagesClient;
}
@ -45,4 +45,9 @@ public class TimeSeriesClient<TDto> : BaseClient, ITimeSeriesClient<TDto> where
return result;
}
public void Dispose()
{
timeSeriesClient.Dispose();
}
}

View File

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

View File

@ -7,6 +7,7 @@ using Refit;
using Persistence.Factories;
using Persistence.Client.Clients.Interfaces.Refit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
namespace Persistence.Client
{
@ -21,20 +22,20 @@ namespace Persistence.Client
PropertyNameCaseInsensitive = true
};
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly ILogger logger;
private readonly IServiceProvider provider;
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.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();
@ -48,6 +49,8 @@ namespace Persistence.Client
/// <returns></returns>
public ISetpointClient GetSetpointClient()
{
var logger = provider.GetRequiredService<ILogger<SetpointClient>>();
var restClient = RestService.For<IRefitSetpointClient>(httpClient, RefitSettings);
var client = new SetpointClient(restClient, logger);
@ -60,6 +63,8 @@ namespace Persistence.Client
/// <returns></returns>
public ITechMessagesClient GetTechMessagesClient()
{
var logger = provider.GetRequiredService<ILogger<TechMessagesClient>>();
var restClient = RestService.For<IRefitTechMessagesClient>(httpClient, RefitSettings);
var client = new TechMessagesClient(restClient, logger);
@ -74,6 +79,8 @@ namespace Persistence.Client
public ITimeSeriesClient<TDto> GetTimeSeriesClient<TDto>()
where TDto : class, new()
{
var logger = provider.GetRequiredService<ILogger<TimeSeriesClient<TDto>>>();
var restClient = RestService.For<IRefitTimeSeriesClient<TDto>>(httpClient, RefitSettings);
var client = new TimeSeriesClient<TDto>(restClient, logger);
@ -86,10 +93,26 @@ namespace Persistence.Client
/// <returns></returns>
public ITimestampedSetClient GetTimestampedSetClient()
{
var logger = provider.GetRequiredService<ILogger<TimestampedSetClient>>();
var restClient = RestService.For<IRefitTimestampedSetClient>(httpClient, RefitSettings);
var client = new TimestampedSetClient(restClient, logger);
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` - Клиент для работы с технологическими сообщениями
- `ITimeSeriesClient` - Клиент для работы с временными данными
- `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени
- `IChangeLogClient` - Клиент для работы с записями ChangeLog
## Использование
Для получения того или иного Persistence - клиента нужно

View File

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

View File

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