59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
using Newtonsoft.Json;
|
|
using System.Net.Http.Json;
|
|
using static System.Net.WebRequestMethods;
|
|
|
|
namespace DigitalData.Core.Client
|
|
{
|
|
public static class HttpExtensions
|
|
{
|
|
public static async Task<string> Text(this HttpResponseMessage response) => await response.Content.ReadAsStringAsync();
|
|
|
|
public static async Task<T?> Json<T>(this HttpResponseMessage response) => await response.Content.ReadFromJsonAsync<T>();
|
|
|
|
public static async Task<dynamic> Json(this HttpResponseMessage response)
|
|
{
|
|
string json = await response.Content.ReadAsStringAsync();
|
|
return JsonConvert.DeserializeObject<dynamic>(json) ?? string.Empty;
|
|
}
|
|
|
|
public static async Task<IEnumerable<dynamic>> JsonList(this HttpResponseMessage response)
|
|
{
|
|
string json = await response.Content.ReadAsStringAsync();
|
|
return JsonConvert.DeserializeObject<dynamic>(json) ?? string.Empty;
|
|
}
|
|
|
|
public static async Task<HttpResponseMessage> Fetch(this string url, string method = Http.Get)
|
|
{
|
|
using HttpClient client = new();
|
|
return method switch
|
|
{
|
|
Http.Get => await client.GetAsync(url),
|
|
_ => throw new NotImplementedException(nameof(method)),
|
|
};
|
|
}
|
|
|
|
public static async void ThenAsync<T>(this Task<T> task, Action<T> toDo)
|
|
{
|
|
var then = await task;
|
|
toDo(then);
|
|
}
|
|
|
|
public static async Task<I> ThenAsync<T, I>(this Task<T> task, Func<T, I> toDo)
|
|
{
|
|
var then = await task;
|
|
return toDo(then);
|
|
}
|
|
|
|
public static async Task<I> ThenAsync<T, I>(this Task<T> task, Func<T, Task<I>> toDoAsync)
|
|
{
|
|
var then = await task;
|
|
return await toDoAsync(then);
|
|
}
|
|
|
|
public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
|
|
{
|
|
foreach (var value in values)
|
|
action(value);
|
|
}
|
|
}
|
|
} |