diff --git a/Persistence.Client/Clients/Base/BaseClient.cs b/Persistence.Client/Clients/Base/BaseClient.cs index bca6f6a..2332cbd 100644 --- a/Persistence.Client/Clients/Base/BaseClient.cs +++ b/Persistence.Client/Clients/Base/BaseClient.cs @@ -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 logger) { this.logger = logger; } diff --git a/Persistence.Client/Clients/ChangeLogClient.cs b/Persistence.Client/Clients/ChangeLogClient.cs new file mode 100644 index 0000000..00aee71 --- /dev/null +++ b/Persistence.Client/Clients/ChangeLogClient.cs @@ -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 logger) : base(logger) + { + this.refitChangeLogClient = refitChangeLogClient; + } + + public async Task ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitChangeLogClient.ClearAndAddRange(idDiscriminator, dtos, token), token); + + return result; + } + + public async Task> GetByDate(Guid idDiscriminator, DateTimeOffset moment, + SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitChangeLogClient.GetByDate(idDiscriminator, moment, filterRequest, paginationRequest, token), token); + + return result; + } + + public async Task> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token) + { + var result = await ExecuteGetResponse>( + async () => await refitChangeLogClient.GetChangeLogForInterval(idDiscriminator, dateBegin, dateEnd, token), token); + + return result; + } + + public async Task Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.Add(idDiscriminator, dto, token), token); + + return result; + } + + public async Task AddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.AddRange(idDiscriminator, dtos, token), token); + + return result; + } + + public async Task Update(DataWithWellDepthAndSectionDto dto, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.Update(dto, token), token); + + return result; + } + + public async Task UpdateRange(IEnumerable dtos, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.UpdateRange(dtos, token), token); + + return result; + } + + public async Task Delete(Guid id, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.Delete(id, token), token); + + return result; + } + + public async Task DeleteRange(IEnumerable ids, CancellationToken token) + { + var result = await ExecutePostResponse( + async () => await refitChangeLogClient.DeleteRange(ids, token), token); + + return result; + } + + public async Task GetDatesRange(Guid idDiscriminator, CancellationToken token) + { + var result = await ExecuteGetResponse( + async () => await refitChangeLogClient.GetDatesRange(idDiscriminator, token), token); + + return result; + } + + public void Dispose() + { + refitChangeLogClient.Dispose(); + } +} diff --git a/Persistence.Client/Clients/IChangeLogClient.cs b/Persistence.Client/Clients/IChangeLogClient.cs deleted file mode 100644 index 06bbc4d..0000000 --- a/Persistence.Client/Clients/IChangeLogClient.cs +++ /dev/null @@ -1,106 +0,0 @@ -using Persistence.Models; -using Persistence.Models.Requests; -using Refit; - -namespace Persistence.Client.Clients; - -/// -/// Интерфейс для тестирования API, предназначенного для работы с записями ChangeLod -/// -public interface IChangeLogClient -{ - private const string BaseRoute = "/api/ChangeLog"; - - /// - /// Импорт с заменой: удаление старых строк и добавление новых - /// - /// - /// - /// - [Post($"{BaseRoute}/replace/{{idDiscriminator}}")] - Task> ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos); - - /// - /// Получение актуальных данных на определенную дату (с пагинацией) - /// - /// - /// - /// параметры запроса фильтрации - /// параметры запроса пагинации - /// - [Get($"{BaseRoute}/moment/{{idDiscriminator}}")] - Task>> GetByDate( - Guid idDiscriminator, - DateTimeOffset moment, - [Query] SectionPartRequest filterRequest, - [Query] PaginationRequest paginationRequest); - - /// - /// Получение исторических данных за определенный период времени - /// - /// - /// - /// - /// - [Get($"{BaseRoute}/history/{{idDiscriminator}}")] - Task>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd); - - /// - /// Добавить одну запись - /// - /// - /// - /// - [Post($"{BaseRoute}/{{idDiscriminator}}")] - Task> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto); - - /// - /// Добавить несколько записей - /// - /// - /// - /// - [Post($"{BaseRoute}/range/{{idDiscriminator}}")] - Task> AddRange(Guid idDiscriminator, IEnumerable dtos); - - /// - /// Обновить одну запись - /// - /// - /// - [Put($"{BaseRoute}")] - Task> Update(DataWithWellDepthAndSectionDto dto); - - /// - /// Обновить несколько записей - /// - /// - /// - [Put($"{BaseRoute}/range")] - Task> UpdateRange(IEnumerable dtos); - - /// - /// Удалить одну запись - /// - /// - /// - [Delete($"{BaseRoute}")] - Task> Delete(Guid id); - - /// - /// Удалить несколько записей - /// - /// - /// - [Delete($"{BaseRoute}/range")] - Task> DeleteRange([Body] IEnumerable ids); - - /// - /// Получение списка дат, в которые происходили изменения (день, месяц, год, без времени) - /// - /// - /// - [Get($"{BaseRoute}/datesRange/{{idDiscriminator}}")] - Task> GetDatesRange(Guid idDiscriminator); - -} diff --git a/Persistence.Client/Clients/Interfaces/IChangeLogClient.cs b/Persistence.Client/Clients/Interfaces/IChangeLogClient.cs new file mode 100644 index 0000000..0d24585 --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/IChangeLogClient.cs @@ -0,0 +1,98 @@ +using Persistence.Models; +using Persistence.Models.Requests; + +namespace Persistence.Client.Clients.Interfaces; + +/// +/// Клиент для работы с записями ChangeLog +/// +public interface IChangeLogClient : IDisposable +{ + /// + /// Добавить одну запись + /// + /// + /// + /// + /// + Task Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token); + + /// + /// Добавить несколько записей + /// + /// + /// + /// + /// + Task AddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + /// + /// Импорт с заменой: удаление старых строк и добавление новых + /// + /// + /// + /// + /// + Task ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + /// + /// Удалить одну запись + /// + /// + /// + /// + Task Delete(Guid id, CancellationToken token); + + /// + /// Удалить несколько записей + /// + /// + /// + /// + Task DeleteRange(IEnumerable ids, CancellationToken token); + + /// + /// Получение актуальных данных на определенную дату (с пагинацией) + /// + /// + /// + /// + /// + /// + /// + Task> GetByDate(Guid idDiscriminator, DateTimeOffset moment, SectionPartRequest filterRequest, PaginationRequest paginationRequest, CancellationToken token); + + /// + /// Получение исторических данных за определенный период времени + /// + /// + /// + /// + /// + /// + Task> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); + + /// + /// Получение списка дат, в которые происходили изменения (день, месяц, год, без времени) + /// + /// + /// + /// + Task GetDatesRange(Guid idDiscriminator, CancellationToken token); + + /// + /// Обновить одну запись + /// + /// + /// + /// + Task Update(DataWithWellDepthAndSectionDto dto, CancellationToken token); + + /// + /// Обновить несколько записей + /// + /// + /// + /// + Task UpdateRange(IEnumerable dtos, CancellationToken token); +} \ No newline at end of file diff --git a/Persistence.Client/Clients/Interfaces/ISetpointClient.cs b/Persistence.Client/Clients/Interfaces/ISetpointClient.cs index 19c5902..295ab87 100644 --- a/Persistence.Client/Clients/Interfaces/ISetpointClient.cs +++ b/Persistence.Client/Clients/Interfaces/ISetpointClient.cs @@ -5,7 +5,7 @@ namespace Persistence.Client.Clients.Interfaces; /// /// Клиент для работы с уставками /// -public interface ISetpointClient +public interface ISetpointClient : IDisposable { /// /// Добавить уставку diff --git a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs index 8da559c..bbf635c 100644 --- a/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITechMessagesClient.cs @@ -1,11 +1,12 @@ using Persistence.Models; +using Persistence.Models.Requests; namespace Persistence.Client.Clients.Interfaces; /// /// Клиент для работы с технологическими сообщениями /// -public interface ITechMessagesClient +public interface ITechMessagesClient : IDisposable { /// /// Добавить новые технологические сообщения @@ -28,7 +29,7 @@ public interface ITechMessagesClient /// /// /// - Task> GetPage(RequestDto request, CancellationToken token); + Task> GetPage(PaginationRequest request, CancellationToken token); /// /// Получить порцию записей, начиная с заданной даты diff --git a/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs b/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs index d6dd199..316c0c9 100644 --- a/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITimeSeriesClient.cs @@ -6,7 +6,7 @@ namespace Persistence.Client.Clients.Interfaces; /// Клиент для работы с временными данными /// /// -public interface ITimeSeriesClient where TDto : class, new() +public interface ITimeSeriesClient : IDisposable where TDto : class, new() { /// /// Добавление записей diff --git a/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs b/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs index ee0ca6e..21fd222 100644 --- a/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs +++ b/Persistence.Client/Clients/Interfaces/ITimestampedSetClient.cs @@ -3,9 +3,12 @@ namespace Persistence.Client.Clients.Interfaces; /// -/// Клиент для работы с данными с отметкой времени +/// Клиент для работы с репозиторием для хранения разных наборов данных рядов. +/// idDiscriminator - идентифицирует конкретный набор данных, прим.: циклы измерения АСИБР, или отчет о DrillTest. +/// idDiscriminator формируют клиенты и только им известно что они обозначают. +/// Так как данные приходят редко, то их прореживания для построения графиков не предусмотрено. /// -public interface ITimestampedSetClient +public interface ITimestampedSetClient : IDisposable { /// /// Записать новые данные diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitChangeLogClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitChangeLogClient.cs new file mode 100644 index 0000000..8408d7e --- /dev/null +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitChangeLogClient.cs @@ -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> ClearAndAddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + [Get($"{BaseRoute}/moment/{{idDiscriminator}}")] + Task>> GetByDate( + Guid idDiscriminator, + DateTimeOffset moment, + [Query] SectionPartRequest filterRequest, + [Query] PaginationRequest paginationRequest, + CancellationToken token); + + [Get($"{BaseRoute}/history/{{idDiscriminator}}")] + Task>> GetChangeLogForInterval(Guid idDiscriminator, DateTimeOffset dateBegin, DateTimeOffset dateEnd, CancellationToken token); + + [Post($"{BaseRoute}/{{idDiscriminator}}")] + Task> Add(Guid idDiscriminator, DataWithWellDepthAndSectionDto dto, CancellationToken token); + + [Post($"{BaseRoute}/range/{{idDiscriminator}}")] + Task> AddRange(Guid idDiscriminator, IEnumerable dtos, CancellationToken token); + + [Put($"{BaseRoute}")] + Task> Update(DataWithWellDepthAndSectionDto dto, CancellationToken token); + + [Put($"{BaseRoute}/range")] + Task> UpdateRange(IEnumerable dtos, CancellationToken token); + + [Delete($"{BaseRoute}")] + Task> Delete(Guid id, CancellationToken token); + + [Delete($"{BaseRoute}/range")] + Task> DeleteRange([Body] IEnumerable ids, CancellationToken token); + + [Get($"{BaseRoute}/datesRange/{{idDiscriminator}}")] + Task> GetDatesRange(Guid idDiscriminator, CancellationToken token); + +} diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs index 97baaba..69a2719 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitSetpointClient.cs @@ -3,10 +3,7 @@ using Refit; namespace Persistence.Client.Clients.Interfaces.Refit; -/// -/// Интерфейс клиента для работы с уставками -/// -public interface IRefitSetpointClient +public interface IRefitSetpointClient : IDisposable { private const string BaseRoute = "/api/setpoint"; diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs index 68968a1..64cb49e 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTechMessagesClient.cs @@ -1,17 +1,15 @@ using Persistence.Models; +using Persistence.Models.Requests; using Refit; namespace Persistence.Client.Clients.Interfaces.Refit { - /// - /// Интерфейс клиента для хранения технологических сообщений - /// - public interface IRefitTechMessagesClient + public interface IRefitTechMessagesClient : IDisposable { private const string BaseRoute = "/api/techMessages"; [Get($"{BaseRoute}")] - Task>> GetPage([Query] RequestDto request, CancellationToken token); + Task>> GetPage([Query] PaginationRequest request, CancellationToken token); [Post($"{BaseRoute}")] Task> AddRange([Body] IEnumerable dtos, CancellationToken token); diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs index 06a1266..3deae09 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimeSeriesClient.cs @@ -2,8 +2,8 @@ using Refit; namespace Persistence.Client.Clients.Interfaces.Refit; -public interface IRefitTimeSeriesClient - where TDto : class, new() +public interface IRefitTimeSeriesClient : IDisposable + where TDto : class, new() { private const string BaseRoute = "/api/dataSaub"; diff --git a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs index b379725..8caeb61 100644 --- a/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs +++ b/Persistence.Client/Clients/Interfaces/Refit/IRefitTimestampedSetClient.cs @@ -3,60 +3,22 @@ using Refit; namespace Persistence.Client.Clients.Interfaces.Refit; -/// -/// Клиент для работы с репозиторием для хранения разных наборов данных рядов. -/// idDiscriminator - идентифицирует конкретный набор данных, прим.: циклы измерения АСИБР, или отчет о DrillTest. -/// idDiscriminator формируют клиенты и только им известно что они обозначают. -/// Так как данные приходят редко, то их прореживания для построения графиков не предусмотрено. -/// -public interface IRefitTimestampedSetClient +public interface IRefitTimestampedSetClient : IDisposable { private const string baseUrl = "/api/TimestampedSet/{idDiscriminator}"; - /// - /// Добавление новых данных - /// - /// Дискриминатор (идентификатор) набора - /// - /// [Post(baseUrl)] Task> AddRange(Guid idDiscriminator, IEnumerable sets, CancellationToken token); - /// - /// Получение данных с фильтрацией. Значение фильтра null - отключен - /// - /// Дискриминатор (идентификатор) набора - /// Фильтр позднее даты - /// Фильтр свойств набора. Можно запросить только некоторые свойства из набора - /// - /// - /// [Get(baseUrl)] Task>> Get(Guid idDiscriminator, [Query] DateTimeOffset? geTimestamp, [Query] IEnumerable? columnNames, int skip, int take, CancellationToken token); - /// - /// Получить последние данные - /// - /// Дискриминатор (идентификатор) набора - /// Фильтр свойств набора. Можно запросить только некоторые свойства из набора - /// - /// [Get($"{baseUrl}/last")] Task>> GetLast(Guid idDiscriminator, [Query] IEnumerable? columnNames, int take, CancellationToken token); - /// - /// Количество записей по указанному набору в БД. Для пагинации. - /// - /// Дискриминатор (идентификатор) набора - /// [Get($"{baseUrl}/count")] Task> Count(Guid idDiscriminator, CancellationToken token); - /// - /// Диапазон дат за которые есть данные - /// - /// Дискриминатор (идентификатор) набора - /// [Get($"{baseUrl}/datesRange")] Task> GetDatesRange(Guid idDiscriminator, CancellationToken token); } diff --git a/Persistence.Client/Clients/SetpointClient.cs b/Persistence.Client/Clients/SetpointClient.cs index 91e10e2..b1df4b4 100644 --- a/Persistence.Client/Clients/SetpointClient.cs +++ b/Persistence.Client/Clients/SetpointClient.cs @@ -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 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(); + } } diff --git a/Persistence.Client/Clients/TechMessagesClient.cs b/Persistence.Client/Clients/TechMessagesClient.cs index 2a7b0e0..c1000b1 100644 --- a/Persistence.Client/Clients/TechMessagesClient.cs +++ b/Persistence.Client/Clients/TechMessagesClient.cs @@ -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 logger) : base(logger) { this.refitTechMessagesClient = refitTechMessagesClient; } - public async Task> GetPage(RequestDto request, CancellationToken token) + public async Task> GetPage(PaginationRequest request, CancellationToken token) { var result = await ExecuteGetResponse>( async () => await refitTechMessagesClient.GetPage(request, token), token); @@ -62,4 +63,9 @@ public class TechMessagesClient : BaseClient, ITechMessagesClient return result; } + + public void Dispose() + { + refitTechMessagesClient.Dispose(); + } } diff --git a/Persistence.Client/Clients/TimeSeriesClient.cs b/Persistence.Client/Clients/TimeSeriesClient.cs index 0b49c81..a3fba7d 100644 --- a/Persistence.Client/Clients/TimeSeriesClient.cs +++ b/Persistence.Client/Clients/TimeSeriesClient.cs @@ -9,7 +9,7 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where { private readonly IRefitTimeSeriesClient timeSeriesClient; - public TimeSeriesClient(IRefitTimeSeriesClient refitTechMessagesClient, ILogger logger) : base(logger) + public TimeSeriesClient(IRefitTimeSeriesClient refitTechMessagesClient, ILogger> logger) : base(logger) { this.timeSeriesClient = refitTechMessagesClient; } @@ -45,4 +45,9 @@ public class TimeSeriesClient : BaseClient, ITimeSeriesClient where return result; } + + public void Dispose() + { + timeSeriesClient.Dispose(); + } } diff --git a/Persistence.Client/Clients/TimestampedSetClient.cs b/Persistence.Client/Clients/TimestampedSetClient.cs index 2e23682..4d40d8b 100644 --- a/Persistence.Client/Clients/TimestampedSetClient.cs +++ b/Persistence.Client/Clients/TimestampedSetClient.cs @@ -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 logger) : base(logger) { this.refitTimestampedSetClient = refitTimestampedSetClient; } @@ -53,4 +53,9 @@ public class TimestampedSetClient : BaseClient, ITimestampedSetClient return result; } + + public void Dispose() + { + refitTimestampedSetClient.Dispose(); + } } diff --git a/Persistence.Client/PersistenceClientFactory.cs b/Persistence.Client/PersistenceClientFactory.cs index 26fb09d..bfaf6fa 100644 --- a/Persistence.Client/PersistenceClientFactory.cs +++ b/Persistence.Client/PersistenceClientFactory.cs @@ -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 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 /// public ISetpointClient GetSetpointClient() { + var logger = provider.GetRequiredService>(); + var restClient = RestService.For(httpClient, RefitSettings); var client = new SetpointClient(restClient, logger); @@ -60,6 +63,8 @@ namespace Persistence.Client /// public ITechMessagesClient GetTechMessagesClient() { + var logger = provider.GetRequiredService>(); + var restClient = RestService.For(httpClient, RefitSettings); var client = new TechMessagesClient(restClient, logger); @@ -74,6 +79,8 @@ namespace Persistence.Client public ITimeSeriesClient GetTimeSeriesClient() where TDto : class, new() { + var logger = provider.GetRequiredService>>(); + var restClient = RestService.For>(httpClient, RefitSettings); var client = new TimeSeriesClient(restClient, logger); @@ -86,10 +93,26 @@ namespace Persistence.Client /// public ITimestampedSetClient GetTimestampedSetClient() { + var logger = provider.GetRequiredService>(); + var restClient = RestService.For(httpClient, RefitSettings); var client = new TimestampedSetClient(restClient, logger); return client; } + + /// + /// Получить клиент для работы с записями ChangeLog + /// + /// + public IChangeLogClient GetChangeLogClient() + { + var logger = provider.GetRequiredService>(); + + var restClient = RestService.For(httpClient, RefitSettings); + var client = new ChangeLogClient(restClient, logger); + + return client; + } } } diff --git a/Persistence.Client/Readme.md b/Persistence.Client/Readme.md index 76e862a..2733b7c 100644 --- a/Persistence.Client/Readme.md +++ b/Persistence.Client/Readme.md @@ -13,6 +13,7 @@ Persistence сервисом посредством обращения к кон - `ITechMessagesClient` - Клиент для работы с технологическими сообщениями - `ITimeSeriesClient` - Клиент для работы с временными данными - `ITimestampedSetClient` - Клиент для работы с данными с отметкой времени +- `IChangeLogClient` - Клиент для работы с записями ChangeLog ## Использование Для получения того или иного Persistence - клиента нужно diff --git a/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs b/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs index 8c3b422..5af0122 100644 --- a/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/ChangeLogControllerTest.cs @@ -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(); - client = persistenceClientFactory.GetClient(); + 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()); // 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()).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()); } diff --git a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs index caa3861..e3219cc 100644 --- a/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs +++ b/Persistence.IntegrationTests/Controllers/TechMessagesControllerTest.cs @@ -32,7 +32,7 @@ namespace Persistence.IntegrationTests.Controllers dbContext.CleanupDbSet(); dbContext.CleanupDbSet(); - 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);