-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebApiInvoker.cs
More file actions
67 lines (56 loc) · 2.1 KB
/
WebApiInvoker.cs
File metadata and controls
67 lines (56 loc) · 2.1 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
namespace CafeBazaar.DeveloperApi
{
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Olive;
class WebApiInvoker
{
public Uri BaseAddress { get; }
public Encoding Encoding { get; set; } = Encoding.UTF8;
public TimeSpan Timeout { get; set; } = 30.Seconds();
public WebApiInvoker(Uri baseAddress) => BaseAddress = baseAddress;
public Task<T> Get<T>(string path) where T : CafeBazaarResultBase, new()
=> Send<T>((client, _) => client.GetAsync(path));
public Task<T> PostJson<T>(string path, object request) where T : CafeBazaarResultBase, new()
{
return Send<T>(async (client, enc) =>
{
var payload = new StringContent(request.ToJson(), Encoding, "text/json");
return await client.PostAsync(path, payload);
});
}
public Task<T> PostForm<T>(string path, object request) where T : CafeBazaarResultBase, new()
{
return Send<T>(async (client, enc) =>
{
var payload = new FormUrlEncodedContent(request.ToDictionary());
return await client.PostAsync(path, payload);
});
}
async Task<T> Send<T>(Func<HttpClient, Encoding, Task<HttpResponseMessage>> requestInitiator) where T : CafeBazaarResultBase, new()
{
try
{
var client = CreateClient();
var message = await requestInitiator(client, Encoding);
return Encoding.GetString(await message.Content.ReadAsByteArrayAsync()).FromJson<T>();
}
catch (Exception ex)
{
return CreateDefault<T>(ex);
}
}
T CreateDefault<T>(Exception ex) where T : CafeBazaarResultBase, new() => new()
{
Error = "Unhandled Exception",
ErrorDescription = ex.Message
};
HttpClient CreateClient() => new()
{
BaseAddress = BaseAddress,
Timeout = Timeout
};
}
}