-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBaseClient.cs
More file actions
49 lines (43 loc) · 1.71 KB
/
Copy pathBaseClient.cs
File metadata and controls
49 lines (43 loc) · 1.71 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
using Ajuna.NetApi;
using Ajuna.NetApi.Model.Types;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace SubstrateNET.RestClient
{
public class BaseClient
{
public class DefaultResponse
{
[JsonProperty("result")]
public string Result { get; set; }
}
protected async Task<T> SendRequestAsync<T>(HttpClient client, string endpoint, string key)
{
return await SendRequestAsync<T>(client, $"{endpoint}?key={Uri.EscapeDataString(key.ToLower())}");
}
protected async Task<T> SendRequestAsync<T>(HttpClient client, string endpoint)
{
var response = await client.GetAsync(endpoint, HttpCompletionOption.ResponseHeadersRead);
return await ProcessResponseAsync<T>(response, endpoint);
}
private async Task<T> ProcessResponseAsync<T>(HttpResponseMessage response, string endpoint)
{
if (response == null || !response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"Invalid response received while sending request to {endpoint}!");
}
string content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrEmpty(content))
{
throw new InvalidOperationException($"Invalid response data received while sending request to {endpoint}!");
}
DefaultResponse json = JsonConvert.DeserializeObject<DefaultResponse>(content);
var resultingObject = (T)Activator.CreateInstance(typeof(T));
var resultObjectBaseType = resultingObject as IType;
resultObjectBaseType.Create(Utils.HexToByteArray(json.Result));
return resultingObject;
}
}
}