-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebQuery.cs
More file actions
183 lines (148 loc) · 7.1 KB
/
WebQuery.cs
File metadata and controls
183 lines (148 loc) · 7.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Schemio.Core;
using Schemio.Core.Helpers;
namespace Schemio.API
{
public abstract class WebQuery<TQueryResult> : BaseQuery<TQueryResult>, IWebQuery
where TQueryResult : IQueryResult
{
protected Uri BaseAddress;
protected WebQuery() : this(string.Empty)
{
}
protected WebQuery(string baseAddress)
{
if (!string.IsNullOrEmpty(baseAddress))
BaseAddress = new Uri(baseAddress);
}
private Func<Uri> UriDelegate = null;
public override bool IsContextResolved() => UriDelegate != null;
public override void ResolveQuery(IDataContext context, IQueryResult parentQueryResult)
{
UriDelegate = GetQuery(context, parentQueryResult);
}
/// <summary>
/// Override to pass custom outgoing headers with the api request.
/// </summary>
/// <returns></returns>
protected virtual IDictionary<string, string> GetRequestHeaders()
{
return new Dictionary<string, string>();
}
/// <summary>
/// Override to get custom incoming headers with the api response.
/// The headers collection will be present on `WebHeaderResult.Headers` when api response includes any of the headers defined in this method.
/// </summary>
/// <returns></returns>
protected virtual IEnumerable<string> GetResponseHeaders()
{ return Enumerable.Empty<string>(); }
/// <summary>
/// Implement to construct the api web query.
/// </summary>
/// <param name="context">Request Context. Always available.</param>
/// <param name="parentApiResult">Result from parent Query. Only available when configured as nested web query. Else will be null.</param>
/// <returns></returns>
protected abstract Func<Uri> GetQuery(IDataContext context, IQueryResult parentApiResult = null);
async Task<IQueryResult> IWebQuery.Run(IHttpClientFactory httpClientFactory, ILogger logger)
{
Constraints.NotNull(httpClientFactory);
logger?.LogInformation($"Run api: {GetType().Name}");
var Uri = UriDelegate();
if (Uri == null)
return null;
using (var client = httpClientFactory.CreateClient())
{
logger?.LogInformation($"Executing web api on thread {Thread.CurrentThread.ManagedThreadId} (task {Task.CurrentId})");
try
{
HttpResponseMessage result;
try
{
if (BaseAddress != null)
client.BaseAddress = BaseAddress;
var requestHeaders = GetRequestHeaders();
if (requestHeaders != null && requestHeaders.Any())
foreach (var header in requestHeaders)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
result = await client.GetAsync(Uri);
var raw = result.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrWhiteSpace(raw))
logger?.LogInformation($"Result.Content of executing web api: {Uri.AbsolutePath} is {raw}");
if (!result.IsSuccessStatusCode)
{
logger?.LogInformation($"Result of executing web api {Uri.AbsolutePath} is not success status code");
return null;
}
if (typeof(TQueryResult).UnderlyingSystemType != null && typeof(TQueryResult).UnderlyingSystemType.Name.Equals(typeof(CollectionResult<>).Name))
{
var typeArgs = typeof(TQueryResult).GetGenericArguments();
var arrType = typeArgs[0].MakeArrayType();
var arrObject = raw.ToObject(arrType);
if (arrObject != null)
{
var resultType = typeof(CollectionResult<>);
var collectionType = resultType.MakeGenericType(typeArgs);
var collectionResult = (TQueryResult)Activator.CreateInstance(collectionType, arrObject);
SetResponseHeaders(result, collectionResult);
return collectionResult;
}
}
else
{
var obj = raw.ToObject(typeof(TQueryResult));
if (obj != null)
{
var resObj = (TQueryResult)obj;
SetResponseHeaders(result, resObj);
return resObj;
}
}
}
catch (TaskCanceledException ex)
{
logger?.LogWarning(ex, $"An error occurred while sending the request. Query URL: {Uri.AbsolutePath}");
}
catch (HttpRequestException ex)
{
logger?.LogWarning(ex, $"An error occurred while sending the request. Query URL: {Uri.AbsolutePath}");
}
}
catch (AggregateException ex)
{
logger?.LogInformation($"Web api {GetType().Name} failed");
foreach (var e in ex.InnerExceptions)
logger?.LogError(e, "");
}
}
return null;
}
private void SetResponseHeaders(HttpResponseMessage response, TQueryResult result)
{
if (response.Headers == null || result == null)
return;
var headers = GetResponseHeaders();
if (headers == null || !headers.Any())
return;
if (!(result is WebHeaderResult webResult))
throw new InvalidOperationException($"{typeof(TQueryResult).Name} should implement from WebHeaderResult for response Headers");
foreach (var header in headers)
{
if (!response.Headers.Any(r => r.Key == header))
continue;
var responseHeader = response.Headers.First(r => r.Key == header);
var value = responseHeader.Value != null && responseHeader.Value.Any()
? responseHeader.Value.ElementAt(0)
: string.Empty;
if (webResult.Headers == null)
webResult.Headers = new Dictionary<string, string>();
webResult.Headers.Add(responseHeader.Key, value);
}
}
}
}