-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathBaseLinkerApiClient.cs
128 lines (107 loc) · 4.44 KB
/
BaseLinkerApiClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.RateLimiting;
using System.Threading.Tasks;
using BaseLinkerApi.Common;
using BaseLinkerApi.Common.JsonConverters;
[assembly: InternalsVisibleTo("BaseLinkerApi.Tests")]
namespace BaseLinkerApi;
// ReSharper disable once UnusedTypeParameter
public interface IRequest<TOutput> where TOutput : ResponseBase
{
}
public interface IRequest : IRequest<ResponseBase>
{
}
public class BaseLinkerException : Exception
{
public BaseLinkerException(string errorCode, string errorMessage, Exception? innerException = null) : base(
$"{errorCode} - {errorMessage}", innerException)
{
ErrorCode = errorCode;
ErrorMessage = errorMessage;
}
public string ErrorCode { get; }
public string ErrorMessage { get; }
}
public interface IBaseLinkerApiClient
{
Task<TOutput> SendAsync<TOutput>(IRequest<TOutput> request, CancellationToken cancellationToken = default)
where TOutput : ResponseBase;
}
public class BaseLinkerApiClient : IBaseLinkerApiClient
{
private readonly HttpClient _httpClient;
private readonly string _token;
public BaseLinkerApiClient(HttpClient httpClient, string token)
{
_httpClient = httpClient;
_token = token;
}
// The API doesn't return TooManyRequests but instead blocks your account so rate limit must be implemented client-side
public FixedWindowRateLimiter TimeLimiter { get; set; } = new(new FixedWindowRateLimiterOptions
{
Window = TimeSpan.FromMinutes(1),
PermitLimit = 100
});
// ReSharper disable once MemberCanBePrivate.Global
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global
public bool UseRequestLimit { get; set; } = true;
public bool ThrowExceptions { get; set; } = true;
private async Task<TOutput> SendImpl<TOutput>(IRequest<TOutput> request,
CancellationToken cancellationToken = default) where TOutput : ResponseBase
{
var jsonSerializerOptions = new JsonSerializerOptions
{ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, AllowTrailingCommas = true };
jsonSerializerOptions.Converters.Add(new BoolConverter());
jsonSerializerOptions.Converters.Add(new StringToNullableDecimalConverter());
var data = new Dictionary<string, string>
{
{ "method", JsonNamingPolicy.CamelCase.ConvertName(request.GetType().Name) },
// https://stackoverflow.com/questions/58570189/is-there-a-built-in-way-of-using-snake-case-as-the-naming-policy-for-json-in-asp
{ "parameters", JsonSerializer.Serialize((object)request, jsonSerializerOptions) }
};
#if NET5_0_OR_GREATER
var content = new FormUrlEncodedContent(data);
#else
// Possible workaround for pre .NET 5 issue with FormUrlEncodedContent length limit
var items = data.Select(i => WebUtility.UrlEncode(i.Key) + "=" + WebUtility.UrlEncode(i.Value));
var content = new StringContent(string.Join("&", items), null, "application/x-www-form-urlencoded");
#endif
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://api.baselinker.com/connector.php")
{
Content = content
};
requestMessage.Headers.Add("X-BLToken", _token);
var responseMessage = await _httpClient.SendAsync(requestMessage, cancellationToken);
var output = await responseMessage.Content.ReadFromJsonAsync<TOutput>(jsonSerializerOptions, cancellationToken);
if (output!.IsSuccessStatus == false && ThrowExceptions)
{
throw new BaseLinkerException(output.ErrorCode!, output.ErrorMessage!);
}
return output;
}
public async Task<TOutput> SendAsync<TOutput>(IRequest<TOutput> request,
CancellationToken cancellationToken = default) where TOutput : ResponseBase
{
var sendTask = SendImpl(request, cancellationToken);
if (!UseRequestLimit)
{
return await sendTask;
}
using var lease = await TimeLimiter.AcquireAsync(cancellationToken: cancellationToken);
if (!lease.IsAcquired)
{
await Task.Delay(TimeLimiter.ReplenishmentPeriod, cancellationToken);
}
return await sendTask;
}
}