Skip to content

Commit

Permalink
fix: HttpClient instance per request
Browse files Browse the repository at this point in the history
  • Loading branch information
Patryk Plewa committed Feb 8, 2023
1 parent 040e8c1 commit cc88171
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/Crowdin.Api/CrowdinApiClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@


using System;
using System.Collections.Generic;
using System.IO;
Expand Down Expand Up @@ -98,7 +98,7 @@ public class CrowdinApiClient : ICrowdinApiClient

private readonly string _baseUrl;
private readonly string _accessToken;
private readonly HttpClient _httpClient;
private readonly Func<HttpClient> _httpClientFactory;
private readonly IRetryService? _retryService;

private static readonly MediaTypeHeaderValue DefaultContentType = MediaTypeHeaderValue.Parse("application/json");
Expand All @@ -124,18 +124,16 @@ public class CrowdinApiClient : ICrowdinApiClient

public CrowdinApiClient(
CrowdinCredentials credentials,
HttpClient? httpClient = null,
Func<HttpClient>? httpClientFactory = null,
IJsonParser? jsonParser = null,
IRetryService? retryService = null)
{
_httpClient = httpClient ?? new HttpClient();
_httpClientFactory = httpClientFactory ?? (() => new HttpClient());
DefaultJsonParser = jsonParser ?? new JsonParser(DefaultJsonSerializerOptions);
_retryService = retryService;

_accessToken = credentials.AccessToken;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", credentials.AccessToken);


// pass base url full
if (!string.IsNullOrWhiteSpace(credentials.BaseUrl))
{
Expand Down Expand Up @@ -308,14 +306,23 @@ public Task<CrowdinApiResult> UploadFile(string subUrl, string filename, Stream
return outResultList.ToArray();
}

private HttpClient GetHttpClientInstance()
{
var httpClient = _httpClientFactory();
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", _accessToken);

return httpClient;
}

private async Task<CrowdinApiResult> SendRequest(HttpRequestMessage request)
{
var result = new CrowdinApiResult();

HttpResponseMessage response =
_retryService != null
? await _retryService.ExecuteRequestAsync(() => _httpClient.SendAsync(request))
: await _httpClient.SendAsync(request);
? await _retryService.ExecuteRequestAsync(() => GetHttpClientInstance().SendAsync(request))
: await GetHttpClientInstance().SendAsync(request);

await CheckDefaultPreconditionsAndErrors(response);
result.StatusCode = response.StatusCode;
Expand Down

0 comments on commit cc88171

Please sign in to comment.