Полностью переписанное api
All checks were successful
Release / pack-and-publish (release) Successful in 36s
All checks were successful
Release / pack-and-publish (release) Successful in 36s
This commit is contained in:
54
YandexMusic.API/Requests/Common/YJsonRequestBuilder.cs
Normal file
54
YandexMusic.API/Requests/Common/YJsonRequestBuilder.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using YandexMusic.API.Converters;
|
||||
using YandexMusic.API.Models.Common;
|
||||
|
||||
namespace YandexMusic.API.Requests.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Строитель запросов с десериализацией JSON-ответа в TResponse.
|
||||
/// </summary>
|
||||
public abstract class YJsonRequestBuilder<TResponse, TParams> : YRequestBuilder<TParams>
|
||||
{
|
||||
protected YJsonRequestBuilder(YandexMusicApi api) : base(api) { }
|
||||
|
||||
protected virtual async Task<TResponse?> DeserializeAsync(HttpResponseMessage response)
|
||||
{
|
||||
var json = await response.Content.ReadAsStringAsync();
|
||||
|
||||
var options = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
Converters = {
|
||||
new JsonStringEnumConverter(JsonNamingPolicy.KebabCaseLower),
|
||||
new IntToStringConverter(),
|
||||
new StringToIntConverter(),
|
||||
new YExecutionContextConverter(Api, Storage),
|
||||
}
|
||||
};
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
var error = JsonSerializer.Deserialize<YErrorResponse>(json, options);
|
||||
throw error ?? new Exception($"Ошибка HTTP {response.StatusCode}: {json}");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<TResponse>(json, options);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"Ошибка десериализации: {ex.Message}\nJSON: {json}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выполняет запрос и возвращает десериализованный объект типа TResponse.
|
||||
/// </summary>
|
||||
public async Task<TResponse?> ExecuteAsync(TParams parameters)
|
||||
{
|
||||
using var response = await ExecuteRawAsync(parameters);
|
||||
return await DeserializeAsync(response);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user