-
Notifications
You must be signed in to change notification settings - Fork 24
/
FuncHandler.cs
65 lines (54 loc) · 2.36 KB
/
FuncHandler.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Keen.Core.Test
{
/// <summary>
/// An <see cref="IHttpMessageHandler"/> that has pre/post/default message handlers functors,
/// as well as a Func<> that produces the actual HttpResponseMessage. These can all be set by
/// test code and will be called if available. There are defaults in place that essentially do
/// nothing, but client code should make sure DefaultAsync gets set, either by a wrapper or
/// explicitly.
/// </summary>
internal class FuncHandler : IHttpMessageHandler
{
internal Action<HttpRequestMessage, CancellationToken> PreProcess = (request, ct) => { };
internal Func<HttpRequestMessage,
CancellationToken,
Task<HttpResponseMessage>> ProduceResultAsync =
(request, ct) => Task.FromResult<HttpResponseMessage>(null);
internal Func<HttpRequestMessage,
HttpResponseMessage,
HttpResponseMessage> PostProcess = (request, response) => response;
internal bool DeferToDefault { get; set; } = true;
public Func<HttpRequestMessage,
CancellationToken,
Task<HttpResponseMessage>> DefaultAsync
{ get; set; }
public async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
PreProcess(request, cancellationToken);
HttpResponseMessage response =
await ProduceResultAsync(request, cancellationToken).ConfigureAwait(false);
// Pass it along down the line if we didn't create a result already.
if (null == response)
{
if (DeferToDefault)
{
response = await DefaultAsync(request, cancellationToken).ConfigureAwait(false);
}
else
{
// Create a dummy successful response so HttpClient doesn't just throw always.
response = await HttpTests.CreateJsonStringResponseAsync(new { dummy = "" })
.ConfigureAwait(false);
}
}
PostProcess(request, response);
return response;
}
}
}