endpoint implementation ...

This commit is contained in:
2026-11-19 18:08:53 +03:30
parent be47468e35
commit bc66d86ed2
7 changed files with 408 additions and 86 deletions
+170 -75
View File
@@ -11,19 +11,16 @@ namespace xApi.Providers
{
//
private readonly ILogger<AzureServices> logger;
private readonly IHttpClientFactory httpClientFactory;
private readonly AzureServiceConfiguration configuration;
public AzureServices(
ILogger<AzureServices> logger,
IHttpClientFactory httpClientFactory,
AzureServiceConfiguration configuration
)
{
//
this.logger = logger;
this.configuration = configuration;
this.httpClientFactory = httpClientFactory;
}
/// <summary>
@@ -37,9 +34,10 @@ namespace xApi.Providers
)
{
//
var json = await GetFromAzureAsync(
AzureEndpoints.ConnectionDataEndpoint,
cancellationToken: cancellationToken
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.ConnectionDataEndpoint
);
//
@@ -47,7 +45,7 @@ namespace xApi.Providers
if (result is null)
{
//
var message = "Failed to parse Azure connection data ...";
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
@@ -58,37 +56,119 @@ namespace xApi.Providers
return result;
}
public async Task<string> GetProjectsAsync(
/// <summary>
/// Retrieve a List of Azure Projects ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureListDto<AzureProjectDto>> GetProjectsAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await GetFromAzureAsync(
AzureEndpoints.ProjectsEndpoint,
cancellationToken: cancellationToken
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.ProjectsEndpoint
);
//
// var result = json.ParseJSON<AzureConnectionDataDto>();
var result = json.ParseJSON<AzureListDto<AzureProjectDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
/// <summary>
/// Retrieve a List of Azure Repositories ...
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<AzureListDto<AzureRepositoryDto>> GetRepositoriesAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.RepositoriesEndpoint
);
//
var result = json.ParseJSON<AzureListDto<AzureRepositoryDto>>();
if (result is null)
{
//
var message = "Failed to parse Azure data ...";
//
logger.LogError(message);
throw new InvalidOperationException(message);
}
//
return result;
}
public async Task<string> GetWorkItemTypesAsync(
CancellationToken cancellationToken = default
)
{
//
var json = await HandleAzureRequest(
method: HttpMethod.Get,
cancellationToken: cancellationToken,
path: AzureEndpoints.WorkItemsODataEndpoint
);
//
return json;
//
// var result = json.ParseJSON<AzureListDto<AzureRepositoryDto>>();
// if (result is null)
// {
// //
// var message = "Failed to parse Azure connection data ...";
// var message = "Failed to parse Azure data ...";
// //
// logger.LogError(message);
// throw new InvalidOperationException(message);
// }
//
return json;
// //
// return result;
}
//
#region Private ...
/// <summary>
/// Handle Running Http Requests ...
/// </summary>
/// <param name="path"></param>
/// <param name="method"></param>
/// <param name="forceJsonValidation"></param>
/// <param name="headers"></param>
/// <param name="queryParams"></param>
/// <param name="routeParams"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> HandleAzureRequest(
string path,
HttpMethod method,
bool forceJsonValidation = true,
IDictionary<string, string>? headers = null,
IDictionary<string, string>? queryParams = null,
IDictionary<string, string>? routeParams = null,
@@ -115,6 +195,7 @@ namespace xApi.Providers
//
// Create Http Client ...
var result = string.Empty;
using (HttpClient client = new())
{
//
@@ -159,91 +240,105 @@ namespace xApi.Providers
// Finalize Url ...
url = $"{url}{path}";
//
// Applying Query String ...
url = url
.ApplyQueryString(queries: queryParams);
//
// Preparing Request ...
var request = new HttpRequestMessage(
method: method,
requestUri: url
);
HttpResponseMessage? response = null;
}
}
private async Task<string> GetFromAzureAsync(
string relativePath,
CancellationToken cancellationToken = default
)
{
//
// Validate PAT ...
var pat = configuration.Pat;
if (string.IsNullOrWhiteSpace(pat))
{
//
logger.LogError("Azure PAT is not configured ...");
throw new InvalidOperationException("Azure PAT is not configured ...");
}
//
// Create Specified Http Client ...
var client = httpClientFactory.CreateClient(Params.AzureHttpClient);
//
// Url ...
var url = $"{client.BaseAddress}{relativePath}";
logger.LogInformation("Url: {url}", url);
//
// Handle Request and Response ...
try
{
//
using var cts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(20));
//
var response = await client.GetAsync(relativePath, cts.Token);
if (!response.IsSuccessStatusCode)
// Applying Headers ...
if (headers is not null &&
headers.Any())
{
//
var content = await response.Content.ReadAsStringAsync(cts.Token);
logger.LogError("Azure returned HTTP {StatusCode}. Content: {Content} ...", response.StatusCode, content);
throw new HttpRequestException($"Azure returned HTTP {(int)response.StatusCode} ...");
foreach (var header in headers)
{
//
if (string.IsNullOrWhiteSpace(header.Value))
{
continue;
}
//
request.Headers.Add(
name: header.Key,
value: header.Value
);
}
}
//
// Reading Content ...
var json = await response.Content.ReadAsStringAsync(cts.Token);
try
{
//
using var cts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(20));
//
// Execute Request ...
var response = await client.SendAsync(
request: request,
cancellationToken: cts.Token
);
//
// Validate Request ...
if (!response.IsSuccessStatusCode)
{
//
var content = await response.Content.ReadAsStringAsync(cts.Token);
//
logger.LogError("Azure returned HTTP {StatusCode}. Content: {Content} ...", response.StatusCode, content);
throw new HttpRequestException($"Azure returned HTTP {(int)response.StatusCode} ...");
}
//
// Reading Content ...
result = await response.Content.ReadAsStringAsync(cts.Token);
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested)
{
//
logger.LogError(ex, "Azure request timed out. Path: {Path} ...", path);
throw new TimeoutException("Azure request timed out ...");
}
catch (Exception ex)
{
//
logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", path);
throw;
}
}
//
// Force Json Validation ...
if (forceJsonValidation)
{
//
// Validating JSON ...
try
{
JsonDocument.Parse(json);
JsonDocument.Parse(result);
}
catch (JsonException ex)
{
//
logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", relativePath);
logger.LogError(ex, "Azure returned non-JSON data. Path: {Path} ...", path);
throw new InvalidDataException("Azure returned non-JSON data ...");
}
}
//
return json;
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException || !cancellationToken.IsCancellationRequested)
{
//
logger.LogError(ex, "Azure request timed out. Path: {Path} ...", relativePath);
throw new TimeoutException("Azure request timed out ...");
}
catch (Exception ex)
{
//
logger.LogError(ex, "Could not connect to Azure. Path: {Path} ...", relativePath);
throw;
}
//
return result;
}
#endregion
}