-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathClient.cs
More file actions
77 lines (61 loc) · 2.58 KB
/
Client.cs
File metadata and controls
77 lines (61 loc) · 2.58 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using ScriptBloxApi.Objects;
namespace ScriptBloxApi
{
internal class Client
{
public class ScriptBloxInternalException(string message) : Exception(message);
public class ScriptBloxApiException(string message) : Exception(message);
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;
#nullable enable
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)
{
string responseText = await response.Content.ReadAsStringAsync();
(bool success, Error? data) = TryDeserialize<Error>(responseText);
if (success && data is not null)
throw new ScriptBloxInternalException(data.Message);
throw new ScriptBloxInternalException($"Error fetching: {response.StatusCode}\n{await response.Content.ReadAsStringAsync()}");
}
string jsonResponse = await response.Content.ReadAsStringAsync();
if (typeof(T) == typeof(string))
return (T)(object)jsonResponse;
T? result = JsonSerializer.Deserialize<T>(jsonResponse);
if (result is null)
throw new ScriptBloxApiException("Deserialization returned null.");
return result;
}
internal static (bool, T?) TryDeserialize<T>(string jsonResponse)
{
try
{
return (true, JsonSerializer.Deserialize<T>(jsonResponse));
}
catch
{
return (false, default);
}
}
#nullable disable
}
}