54 lines
1.9 KiB
C#
54 lines
1.9 KiB
C#
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);
|
||
}
|
||
} |