-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathClient.cs
47 lines (38 loc) · 1.62 KB
/
Client.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
namespace ScriptBloxApi
{
internal class Client
{
private static readonly Lazy<HttpClient> LazyClient = new(() =>
{
HttpClient client = new()
{
Timeout = TimeSpan.FromSeconds(30)
};
client.DefaultRequestHeaders.Add("User-Agent", "IrisAgent ScriptBloxApi/1.0");
client.DefaultRequestHeaders.Add("Accept", "application/json");
return client;
});
internal static HttpClient HttpClient => LazyClient.Value;
internal static async Task<T> Get<T>(string endpoint, (string Key, string Value)[]? queryParams)
{
string queryString = string.Join("&", queryParams?.Select(kvp => $"{kvp.Key}={kvp.Value}") ?? []);
if (!string.IsNullOrEmpty(queryString))
queryString = "?" + queryString;
HttpRequestMessage request = new(HttpMethod.Get, $"https://scriptblox.com/api/{endpoint}{queryString}");
HttpResponseMessage response = await HttpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
throw new Exception(
$"Error fetching: {response.StatusCode}\n{await response.Content.ReadAsStringAsync()}");
string jsonResponse = await response.Content.ReadAsStringAsync();
if (typeof(T) == typeof(string))
return (T)(object)jsonResponse;
return JsonSerializer.Deserialize<T>(jsonResponse);
}
}
}