FeedDataverseBQ/Migration/Services/Implementation/GoogleBigQueryClientFactory.cs

61 lines
2.1 KiB
C#
Raw Normal View History

2025-03-24 16:14:46 -04:00
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Google.Cloud.BigQuery.V2;
using System.Net.Http.Headers;
namespace Migration.Services;
public class CustomHttpClientFactory : HttpClientFactory
{
private readonly string userAgent;
public CustomHttpClientFactory(string userAgent)
{
if (string.IsNullOrWhiteSpace(userAgent))
{
throw new ArgumentException("User-Agent cannot be null or empty", nameof(userAgent));
}
this.userAgent = userAgent;
}
public new ConfigurableHttpClient CreateHttpClient(CreateHttpClientArgs args)
{
var httpClient = base.CreateHttpClient(args);
httpClient.DefaultRequestHeaders.UserAgent.Clear();
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(userAgent, "1.0"));
return httpClient;
}
}
public class GoogleBigQueryClientFactory : IGoogleBigQueryClientFactory
{
private readonly Lazy<BigQueryClient> bigqueryClient;
public GoogleBigQueryClientFactory(IConfiguration configuration)
{
bigqueryClient = new Lazy<BigQueryClient>(CreateClient(configuration));
}
public BigQueryClient CreateClient(IConfiguration configuration)
{
var projectId = configuration.GetValue<string>("BigQuery:ProjectId") ?? throw new Exception("Nie podano identyfikatora projektu Google.");
var userAgent = configuration.GetValue<string>("BigQuery:UserAgent") ?? throw new Exception("Nie podano UserAgent.");
var credentialFile = configuration.GetValue<string>("GoogleCredentialFile") ?? throw new Exception("Nie podano ścieżki do pliku GoogleCredentials.");
var credential = GoogleCredential.FromFile(credentialFile);
var httpClientFactory = new CustomHttpClientFactory(userAgent);
return new BigQueryClientBuilder
{
ProjectId = projectId,
Credential = credential,
2025-03-24 16:21:48 -04:00
HttpClientFactory = httpClientFactory,
ApplicationName = userAgent
2025-03-24 16:14:46 -04:00
}.Build();
}
public BigQueryTable GetTable(string datasetId, string tableId)
{
return bigqueryClient.Value.GetTable(datasetId, tableId);
}
}