-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathhits_searcher.dart
347 lines (309 loc) · 9.01 KB
/
hits_searcher.dart
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import 'dart:async';
import 'package:algolia_insights/algolia_insights.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:rxdart/rxdart.dart';
import '../client_options.dart';
import '../disposable.dart';
import '../disposable_mixin.dart';
import '../filter_state.dart';
import '../logger.dart';
import '../model/multi_search_response.dart';
import '../model/multi_search_state.dart';
import '../model/search_request.dart';
import '../service/algolia_hits_search_service.dart';
import '../service/hits_search_service.dart';
/// Algolia Helpers main entry point, the component handling search requests
/// and managing search sessions.
///
/// [HitsSearcher] component has the following behavior:
///
/// 1. Distinct state changes (including initial state) trigger search operation
/// 2. State changes are debounced
/// 3. On new search request, previous ongoing search calls are cancelled
///
/// ## Create Hits Searcher
///
/// Instantiate [HitsSearcher] using default constructor:
///
/// ```dart
/// final hitsSearcher = HitsSearcher(
/// applicationID: 'MY_APPLICATION_ID',
/// apiKey: 'MY_API_KEY',
/// indexName: 'MY_INDEX_NAME',
/// );
/// ```
/// Or, using [HitsSearcher.create] factory:
///
/// ```dart
/// final hitsSearcher = HitsSearcher.create(
/// applicationID: 'MY_APPLICATION_ID',
/// apiKey: 'MY_API_KEY',
/// state: const SearchState(indexName: 'MY_INDEX_NAME', query: 'shoes'),
/// );
/// ```
///
/// ## Run search requests
///
/// Execute search queries using [query] method:
///
/// ```dart
/// hitsSearcher.query('book');
/// ```
///
/// Or, using [applyState] for more parameters:
///
/// ```dart
/// hitsSearcher.applyState((state) => state.copyWith(query: 'book', page: 0));
/// ```
///
/// ## Get search state
///
/// Listen to [state] to get search state changes:
///
/// ```dart
/// hitsSearcher.state.listen((searchState) => print(searchState.query));
/// ```
///
/// ## Get search results
///
/// Listen to [responses] to get search responses:
///
/// ```dart
/// hitsSearcher.responses.listen((response) {
/// print('${response.nbHits} hits found');
/// for (var hit in response.hits) {
/// print("> ${hit['objectID']}");
/// }
/// });
/// ```
///
/// Use [snapshot] to get the latest search response value submitted
/// by [responses] stream:
///
/// ```dart
/// var response = hitsSearcher.snapshot();
/// ```
///
/// ## Dispose
///
/// Call [dispose] to release underlying resources:
///
/// ```dart
/// hitsSearcher.dispose();
/// ```
abstract interface class HitsSearcher implements Disposable, EventDataDelegate {
/// HitsSearcher's factory.
factory HitsSearcher({
required String applicationID,
required String apiKey,
required String indexName,
bool disjunctiveFacetingEnabled = true,
Duration debounce = const Duration(milliseconds: 100),
bool insights = false,
ClientOptions? options,
}) =>
_HitsSearcher(
applicationID: applicationID,
apiKey: apiKey,
state: SearchState(
indexName: indexName,
clickAnalytics: true,
isDisjunctiveFacetingEnabled: disjunctiveFacetingEnabled,
),
debounce: debounce,
insights: insights,
options: options,
);
/// HitsSearcher's factory.
factory HitsSearcher.create({
required String applicationID,
required String apiKey,
required SearchState state,
bool disjunctiveFacetingEnabled = true,
Duration debounce = const Duration(milliseconds: 100),
bool insights = false,
ClientOptions? options,
}) =>
_HitsSearcher(
applicationID: applicationID,
apiKey: apiKey,
state: state.copyWith(clickAnalytics: true),
disjunctiveFacetingEnabled: disjunctiveFacetingEnabled,
debounce: debounce,
insights: insights,
options: options,
);
/// Creates [HitsSearcher] using a custom [HitsSearchService].
@internal
factory HitsSearcher.custom(
HitsSearchService searchService,
EventTracker? eventTracker,
SearchState state, [
Duration debounce = const Duration(milliseconds: 100),
]) =>
_HitsSearcher.create(
searchService,
eventTracker,
state,
debounce,
);
HitsEventTracker? get eventTracker;
/// Search state stream
Stream<SearchState> get state;
/// Search results stream
Stream<SearchResponse> get responses;
/// Set query string.
void query(String query);
/// Get current [SearchState].
SearchState snapshot();
/// Get latest [SearchResponse].
SearchResponse? get lastResponse;
/// Apply search state configuration.
void applyState(SearchState Function(SearchState state) config);
/// Re-run the last search query
void rerun();
}
/// Extensions over [HitsSearcher]
extension SearcherExt on HitsSearcher {
/// Creates a connection between [HitsSearcher] and [FilterState].
StreamSubscription connectFilterState(FilterState filterState) =>
filterState.filters.listen(
(filters) => applyState(
(state) => state.copyWith(filterGroups: filters.toFilterGroups()),
),
);
}
/// Default implementation of [HitsSearcher].
final class _HitsSearcher with DisposableMixin implements HitsSearcher {
/// HitsSearcher's factory.
factory _HitsSearcher({
required String applicationID,
required String apiKey,
required SearchState state,
bool disjunctiveFacetingEnabled = true,
Duration debounce = const Duration(milliseconds: 100),
bool insights = false,
ClientOptions? options,
}) {
final service = AlgoliaHitsSearchService(
applicationID: applicationID,
apiKey: apiKey,
options: options,
);
EventTracker? eventTracker;
if (insights) {
eventTracker = Insights(
applicationID: applicationID,
apiKey: apiKey,
);
}
return _HitsSearcher.create(
service,
eventTracker,
state.copyWith(isDisjunctiveFacetingEnabled: disjunctiveFacetingEnabled),
debounce,
);
}
/// HitSearcher's constructor, for internal and test use only.
_HitsSearcher.create(
HitsSearchService searchService,
EventTracker? eventTracker,
SearchState state, [
Duration debounce = const Duration(milliseconds: 100),
]) : this._(
searchService,
eventTracker,
BehaviorSubject.seeded(SearchRequest(state)),
debounce,
);
/// HitsSearcher's private constructor
_HitsSearcher._(
this.searchService,
EventTracker? eventTracker,
this._request,
this.debounce,
) {
if (eventTracker != null) {
this.eventTracker = HitsEventTracker(eventTracker, this);
}
_subscriptions.add(_responses.connect());
}
/// Search state stream
@override
Stream<SearchState> get state =>
_request.stream.map((request) => request.state);
/// Search results stream
@override
Stream<SearchResponse> get responses => _responses;
/// Service handling search requests
final HitsSearchService searchService;
@override
HitsEventTracker? eventTracker;
/// Search state debounce duration
final Duration debounce;
/// Search state subject
final BehaviorSubject<SearchRequest<SearchState>> _request;
/// Search responses subject
late final _responses = _request.stream
.debounceTime(debounce)
.distinct()
.switchMap((req) => Stream.fromFuture(searchService.search(req.state)))
.doOnData((value) {
lastResponse = value;
eventTracker?.viewedObjects(
eventName: 'Hits Viewed',
objectIDs: value.hits.map((hit) => hit['objectID'].toString()).toList(),
);
}).publish();
/// Events logger
final Logger _log = algoliaLogger('HitsSearcher');
/// Streams subscriptions composite.
final CompositeSubscription _subscriptions = CompositeSubscription();
/// Set query string.
@override
void query(String query) {
_updateState((state) => state.copyWith(query: query));
}
/// Get current [SearchState].
@override
SearchState snapshot() => _request.value.state;
/// Get latest search response
@override
SearchResponse? lastResponse;
/// Apply search state configuration.
@override
void applyState(SearchState Function(SearchState state) config) {
_updateState((state) => config(state));
}
/// Apply changes to the current state
void _updateState(SearchState Function(SearchState state) apply) {
if (_request.isClosed) {
_log.warning('modifying disposed instance');
return;
}
final current = _request.value;
final newState = apply(current.state);
_request.sink.add(SearchRequest(newState));
}
@override
void rerun() {
final current = _request.value;
final request = current.copyWith(
state: current.state,
attempts: current.attempts + 1,
);
_log.fine('Rerun request: $request');
_request.sink.add(request);
}
@override
void doDispose() {
_log.fine('HitsSearcher disposed');
_request.close();
_subscriptions.dispose();
}
@override
String get indexName => snapshot().indexName;
@override
String? get queryID => lastResponse?.queryID;
}