/
PaginationBaseService.cs
250 lines (222 loc) · 8.73 KB
/
PaginationBaseService.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
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Net.Http;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace LightQuery.Client
{
public class PaginationBaseService<T> : INotifyPropertyChanged, IDisposable
{
private readonly string _baseUrl;
private readonly Func<string, CancellationToken, Task<HttpResponseMessage>> _getHttpAsync;
private int _page = 1;
private int _pageSize = 20;
private string _sortProperty;
private bool _sortDescending;
private string _thenSortProperty;
private bool _thenSortDescending;
private readonly Dictionary<string, string> _additionalQueryParameters = new Dictionary<string, string>();
private readonly BehaviorSubject<string> _requestUrl = new BehaviorSubject<string>(null);
private readonly ReplaySubject<PaginationResult<T>> _paginationResultSource = new ReplaySubject<PaginationResult<T>>(1);
private readonly BehaviorSubject<bool> _requestRunningSource = new BehaviorSubject<bool>(false);
private readonly Subject<string> _forceRefreshSource = new Subject<string>();
private IDisposable _querySubscription;
public PaginationBaseService(string baseUrl,
Func<string, Task<HttpResponseMessage>> getHttpAsync,
DefaultPaginationOptions options = null)
: this(baseUrl, (url, _) => getHttpAsync == null ? throw new ArgumentNullException(nameof(getHttpAsync)) : getHttpAsync(url), options)
{ }
public PaginationBaseService(string baseUrl,
Func<string, CancellationToken, Task<HttpResponseMessage>> getHttpAsync,
DefaultPaginationOptions options = null)
{
_baseUrl = baseUrl ?? string.Empty;
_getHttpAsync = getHttpAsync ?? throw new ArgumentNullException(nameof(getHttpAsync));
PaginationResult = _paginationResultSource.AsObservable();
RequestRunning = _requestRunningSource.AsObservable();
if (options != null)
{
Page = options.Page;
PageSize = options.PageSize;
SetSortProperty(options.SortProperty);
SortDescending = options.SortDescending;
SetThenSortProperty(options.ThenSortProperty);
ThenSortDescending = options.ThenSortDescending;
}
SetupQuerySubscription();
BuildUrl();
}
public event PropertyChangedEventHandler PropertyChanged;
public string BaseUrl => _baseUrl;
public IObservable<PaginationResult<T>> PaginationResult { get; }
public IObservable<bool> RequestRunning { get; }
public int Page
{
get => _page;
set => SetProperty(ref _page, value < 1 ? 1 : value);
}
public int PageSize
{
get => _pageSize;
set => SetProperty(ref _pageSize, value < 1 ? 1 : value);
}
public string SortProperty => _sortProperty;
public bool SortDescending
{
get => _sortDescending;
set => SetProperty(ref _sortDescending, value);
}
public string ThenSortProperty => _thenSortProperty;
public bool ThenSortDescending
{
get => _thenSortDescending;
set => SetProperty(ref _thenSortDescending, value);
}
public void Dispose()
{
_querySubscription.Dispose();
}
private void SetupQuerySubscription()
{
_querySubscription = Observable.Merge(_forceRefreshSource, _requestUrl.DistinctUntilChanged())
.Where(url => url != null)
.Select(url =>
{
return Observable.DeferAsync(async token =>
{
_requestRunningSource.OnNext(true);
var response = await _getHttpAsync(url, token);
return Observable.Return(response);
});
})
.Switch()
.Where(httpResponse => httpResponse != null)
.Subscribe(async httpResponse =>
{
_requestRunningSource.OnNext(false);
var responseData = new HttpResponseMessageData
{
RequestedPage = Page,
Response = httpResponse
};
var readResponse = await ResponseDeserializer<T>.DeserializeResponse(responseData);
if (readResponse == null)
{
return;
}
if (readResponse.NewPageSuggestion != 0)
{
Page = readResponse.NewPageSuggestion;
}
if (readResponse.DeserializedValue?.Data != null)
{
_paginationResultSource.OnNext(readResponse.DeserializedValue);
}
});
}
private void SetProperty<TProperty>(ref TProperty storage, TProperty value, [CallerMemberName] string propertyName = null)
{
if (!Equals(value, storage))
{
storage = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
BuildUrl();
}
}
public void SetSortProperty(string propertyName)
{
if (propertyName == null)
{
SetProperty(ref _sortProperty, null, nameof(SortProperty));
}
else
{
CheckSortPropertyValidity(propertyName);
SetProperty(ref _sortProperty, propertyName, nameof(SortProperty));
}
}
public void SetSortProperty<TKey>(Expression<Func<T, TKey>> sortProperty)
{
if (sortProperty == null)
{
SetSortProperty(null);
}
else
{
var parameterName = ExpressionPropertyAccessor.GetPropertyNameFromExpression(sortProperty);
SetSortProperty(parameterName);
}
}
public void SetThenSortProperty(string propertyName)
{
if (propertyName == null)
{
SetProperty(ref _thenSortProperty, null, nameof(ThenSortProperty));
}
else
{
CheckSortPropertyValidity(propertyName);
SetProperty(ref _thenSortProperty, propertyName, nameof(ThenSortProperty));
}
}
public void SetThenSortProperty<TKey>(Expression<Func<T, TKey>> sortProperty)
{
if (sortProperty == null)
{
SetThenSortProperty(null);
}
else
{
var parameterName = ExpressionPropertyAccessor.GetPropertyNameFromExpression(sortProperty);
SetThenSortProperty(parameterName);
}
}
private void CheckSortPropertyValidity(string propertyName)
{
var propertyExistsOnType = ExpressionPropertyAccessor.PropertyExistsOnType<T>(propertyName);
if (!propertyExistsOnType)
{
var typeName = typeof(T).GetTypeInfo().Name;
throw new ArgumentException($"The property \"{propertyName}\" does not exist on type {typeName}", nameof(propertyName));
}
}
public void SetQueryParameter(string name, string value = null)
{
_additionalQueryParameters[name] = value;
BuildUrl();
}
public string GetQueryParameter(string name)
{
if (_additionalQueryParameters.ContainsKey(name))
{
return _additionalQueryParameters[name];
}
return null;
}
public void RemoveQueryParameter(string name)
{
if (_additionalQueryParameters.ContainsKey(name))
{
_additionalQueryParameters.Remove(name);
BuildUrl();
}
}
private void BuildUrl()
{
var query = QueryBuilder.Build(Page, PageSize, SortProperty, SortDescending, ThenSortProperty, ThenSortDescending, _additionalQueryParameters);
var url = $"{_baseUrl}{query}";
_requestUrl.OnNext(url);
}
public void ForceRefresh()
{
var lastUrl = _requestUrl.Value;
_forceRefreshSource.OnNext(lastUrl);
}
}
}