-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataServiceClient.cs
More file actions
204 lines (169 loc) · 6.5 KB
/
DataServiceClient.cs
File metadata and controls
204 lines (169 loc) · 6.5 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
namespace DataServices.Client;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Threading.Tasks;
using Common;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Reflection;
public class DataServiceClient<TEntity> : IDataServiceClient<TEntity> where TEntity : class
{
private readonly string _baseUrl;
private readonly ILogger<DataServiceClient<TEntity>> _logger;
private readonly IHttpClientFunction _httpClientFunction;
private readonly PropertyInfo _keyInfo;
public DataServiceClient(ILogger<DataServiceClient<TEntity>> logger, DataServiceResolver dataServiceResolver, IHttpClientFunction httpClientFunction)
{
_baseUrl = dataServiceResolver.GetDataServiceUrl(typeof(TEntity));
if (string.IsNullOrEmpty(_baseUrl))
{
throw new InvalidDataException($"Unable to resolve DataServiceUrl for Data Service of type: {typeof(TEntity).FullName}");
}
_httpClientFunction = httpClientFunction;
_logger = logger;
_keyInfo = ReflectionUtilities.GetKey<TEntity>();
}
public async Task<IEnumerable<TEntity>> GetAll()
{
var jsonString = await _httpClientFunction.SendGet(_baseUrl);
if (string.IsNullOrEmpty(jsonString)) return [];
return JsonSerializer.Deserialize<IEnumerable<TEntity>>(jsonString);
}
public async Task<IEnumerable<TEntity>> GetByFilter(Expression<Func<TEntity, bool>> predicate)
{
var jsonString = await GetJsonStringByFilter(predicate);
if (string.IsNullOrEmpty(jsonString))
{
return [];
}
IEnumerable<TEntity> result = JsonSerializer.Deserialize<IEnumerable<TEntity>>(jsonString);
return result;
}
public async Task<IEnumerable<TEntity>> GetByFilter(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, object>> orderBy, int take)
{
var result = await GetByFilter(predicate);
var orderByFunction = orderBy.Compile();
return result.OrderBy(orderByFunction).Take(take).ToList();
}
public virtual async Task<TEntity> GetSingle(string id)
{
try
{
var jsonString = await _httpClientFunction.SendGet(UrlBuilder(_baseUrl, id));
if (string.IsNullOrEmpty(jsonString))
{
_logger.LogWarning("Response for get single from data service of type: {TypeName} was empty", typeof(TEntity).FullName);
return null;
}
if (jsonString == "No Data Found")
{
return null;
}
TEntity result = JsonSerializer.Deserialize<TEntity>(jsonString);
return result;
}
catch (WebException wex)
{
HttpWebResponse response = (HttpWebResponse)wex.Response;
if (response.StatusCode! == HttpStatusCode.NotFound)
{
return null;
}
_logger.LogError(wex, "An Exception Happened while calling data service API");
throw;
}
}
public async Task<TEntity> GetSingleByFilter(Expression<Func<TEntity, bool>> predicate)
{
var jsonString = await GetJsonStringByFilter(predicate, true);
if (string.IsNullOrEmpty(jsonString))
{
return null!;
}
TEntity result = JsonSerializer.Deserialize<TEntity>(jsonString)!;
return result!;
}
public async Task<bool> Delete(string id)
{
var result = await _httpClientFunction.SendDelete(UrlBuilder(_baseUrl, id));
return result;
}
public async Task<bool> AddRange(IEnumerable<TEntity> entities)
{
var jsonString = JsonSerializer.Serialize<IEnumerable<TEntity>>(entities);
if (string.IsNullOrEmpty(jsonString))
{
_logger.LogWarning("Unable to serialize post request body for creating entity of type {EntityType}", typeof(TEntity).FullName);
return false;
}
var result = await _httpClientFunction.SendPost(_baseUrl, jsonString);
if (result.StatusCode != HttpStatusCode.OK)
{
return false;
}
return true;
}
public async Task<bool> Add(TEntity entity)
{
var jsonString = JsonSerializer.Serialize<TEntity>(entity);
if (string.IsNullOrEmpty(jsonString))
{
_logger.LogWarning("Unable to serialize post request body for creating entity of type {EntityType}", typeof(TEntity).FullName);
return false;
}
var result = await _httpClientFunction.SendPost(_baseUrl, jsonString);
if (result.StatusCode != HttpStatusCode.OK)
{
return false;
}
return true;
}
public async Task<bool> Update(TEntity entity)
{
var jsonString = JsonSerializer.Serialize<TEntity>(entity);
var key = _keyInfo.GetValue(entity)?.ToString() ?? string.Empty;
if (string.IsNullOrEmpty(jsonString))
{
_logger.LogWarning("Unable to serialize put request body for creating entity of type {EntityType}", typeof(TEntity).FullName);
return false;
}
var result = await _httpClientFunction.SendPut(UrlBuilder(_baseUrl, key), jsonString);
if (result.StatusCode != HttpStatusCode.OK)
{
return false;
}
return true;
}
private async Task<string> GetJsonStringByFilter(Expression<Func<TEntity, bool>> predicate, bool returnOneRecord = false)
{
try
{
//Resolves the constants
var expr = new ClosureResolver().Visit(predicate);
var queryItems = new Dictionary<string, string> { { "query", expr.ToString() } };
if (returnOneRecord)
{
queryItems.Add("single", "true");
}
var jsonString = await _httpClientFunction.SendGet(_baseUrl, queryItems);
return jsonString;
}
catch (WebException wex)
{
HttpWebResponse response = (HttpWebResponse)wex.Response;
if (response.StatusCode! == HttpStatusCode.NotFound)
{
return null;
}
_logger.LogError(wex, "An Exception Happened while calling data service API");
throw;
}
}
private static string UrlBuilder(string baseUrl, string argument)
{
baseUrl = baseUrl.TrimEnd('/');
argument = argument.TrimStart('/');
return string.Format("{0}/{1}", baseUrl, argument);
}
}