| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Text; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | using Services.ApiServices.ApiSupplierRequestLog; |
| | | 6 | | |
| | | 7 | | namespace Services.ApiServices.JapartsApi; |
| | | 8 | | |
| | | 9 | | public sealed class JapartsHttpClient |
| | | 10 | | { |
| | 1 | 11 | | private static readonly Encoding Cp1251 = Encoding.GetEncoding(1251); |
| | | 12 | | private readonly IHttpClientFactory _factory; |
| | | 13 | | private readonly JapartsConfig _config; |
| | | 14 | | private readonly ApiSupplierRequestLogStore _logs; |
| | | 15 | | |
| | 3 | 16 | | public JapartsHttpClient(IHttpClientFactory factory, JapartsConfig config, ApiSupplierRequestLogStore logs) => |
| | 3 | 17 | | (_factory, _config, _logs) = (factory, config, logs); |
| | | 18 | | |
| | | 19 | | public async Task<JsonDocument> SendAsync(string action, IReadOnlyDictionary<string, string?>? parameters = null, |
| | | 20 | | CancellationToken ct = default) |
| | | 21 | | { |
| | 3 | 22 | | if (string.IsNullOrWhiteSpace(_config.Login) || string.IsNullOrWhiteSpace(_config.Password)) |
| | 0 | 23 | | throw new JapartsApiException("Не заданы Japarts:Login или Japarts:Password."); |
| | 3 | 24 | | var query = new Dictionary<string, string?> { ["id"] = "ws", ["action"] = action, ["login"] = _config.Login, ["p |
| | 45 | 25 | | if (parameters != null) foreach (var pair in parameters) query[pair.Key] = pair.Value; |
| | 3 | 26 | | var uri = new UriBuilder(_config.BaseUrl); |
| | 51 | 27 | | uri.Query = string.Join("&", query.Where(x => x.Value != null).Select(x => $"{Uri.EscapeDataString(x.Key)}={Uri. |
| | 3 | 28 | | var timer = Stopwatch.StartNew(); |
| | 3 | 29 | | HttpResponseMessage? response = null; |
| | 3 | 30 | | string body = string.Empty; |
| | | 31 | | try |
| | | 32 | | { |
| | 3 | 33 | | response = await _factory.CreateClient("JapartsApi").GetAsync(uri.Uri, ct); |
| | 1 | 34 | | var bytes = await response.Content.ReadAsByteArrayAsync(ct); |
| | 1 | 35 | | body = Cp1251.GetString(bytes); |
| | 1 | 36 | | _logs.Add("Japarts", "GET", uri.Uri.GetLeftPart(UriPartial.Path), (int)response.StatusCode, timer, uri.Query |
| | 1 | 37 | | if (!response.IsSuccessStatusCode) throw new JapartsApiException($"Japarts вернул HTTP {(int)response.Status |
| | 1 | 38 | | var json = JsonDocument.Parse(body); |
| | 1 | 39 | | if (json.RootElement.ValueKind == JsonValueKind.Object && json.RootElement.TryGetProperty("error", out var e |
| | 0 | 40 | | throw new JapartsApiException($"Japarts: {error.GetString()}"); |
| | 1 | 41 | | return json; |
| | | 42 | | } |
| | 0 | 43 | | catch (JsonException ex) { throw new JapartsApiException($"Japarts вернул некорректный JSON: {ex.Message}"); } |
| | 3 | 44 | | finally { response?.Dispose(); } |
| | 1 | 45 | | } |
| | | 46 | | } |