-
Notifications
You must be signed in to change notification settings - Fork 19
/
facet_searcher.dart
291 lines (262 loc) · 7.77 KB
/
facet_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
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 '../logger.dart';
import '../model/multi_search_response.dart';
import '../model/multi_search_state.dart';
import '../model/search_request.dart';
import '../service/algolia_facet_search_service.dart';
import '../service/facet_search_service.dart';
/// Algolia Helpers main entry point for facet search requests and managing
/// search sessions.
///
/// [FacetSearcher] is a component that facilitates facet search operations on
/// an Algolia index. It handles distinct state changes, including the initial
/// state, to trigger facet search operations. The state changes are debounced
/// to ensure that only the last state change triggers the search operation.
/// Additionally, on new facet search requests, any ongoing search calls for
/// the previous request are cancelled, allowing only the latest facet search
/// results to be processed.
///
/// ## Create Facet Searcher
///
/// Instantiate [FacetSearcher] using the default constructor:
///
/// ```dart
/// final facetSearcher = FacetSearcher(
/// applicationID: 'MY_APPLICATION_ID',
/// apiKey: 'MY_API_KEY',
/// indexName: 'MY_INDEX_NAME',
/// facet: 'MY_FACET_ATTRIBUTE',
/// );
/// ```
///
/// Or, using the [FacetSearcher.create] factory:
///
/// ```dart
/// final facetSearcher = FacetSearcher.create(
/// applicationID: 'MY_APPLICATION_ID',
/// apiKey: 'MY_API_KEY',
/// state: FacetSearchState(
/// searchState: SearchState(indexName: 'MY_INDEX_NAME'),
/// facet: 'MY_FACET_ATTRIBUTE',
/// ),
/// );
/// ```
///
/// ## Run facet search queries
///
/// Execute facet search queries using the [query] method:
///
/// ```dart
/// facetSearcher.query('book');
/// ```
///
/// Or, use the [applyState] method for more parameters:
///
/// ```dart
/// facetSearcher.applyState((state) => state.copyWith(query: 'book'));
/// ```
///
/// ## Get facet search state
///
/// Listen to the [state] stream to get facet search state changes:
///
/// ```dart
/// facetSearcher.state.listen((facetSearchState) =>
/// print(facetSearchState.query));
/// ```
///
/// ## Get facet search results
///
/// Listen to the [responses] stream to get facet search responses:
///
/// ```dart
/// facetSearcher.responses.listen((response) {
/// print('${response.nbHits} hits found');
/// for (var hit in response.hits) {
/// print("> ${hit['objectID']}");
/// }
/// });
/// ```
///
/// Use [snapshot] to get the latest facet search response value submitted
/// by the [responses] stream:
///
/// ```dart
/// var response = facetSearcher.snapshot();
/// ```
///
/// ## Dispose
///
/// Call [dispose] to release underlying resources:
///
/// ```dart
/// facetSearcher.dispose();
/// ```
abstract interface class FacetSearcher implements Disposable {
/// FacetSearcher's factory.
factory FacetSearcher({
required String applicationID,
required String apiKey,
required String indexName,
required String facet,
Duration debounce = const Duration(milliseconds: 100),
ClientOptions? options,
}) =>
_FacetSearcher(
applicationID: applicationID,
apiKey: apiKey,
state: FacetSearchState(
searchState: SearchState(indexName: indexName),
facet: facet,
),
debounce: debounce,
options: options,
);
/// HitsSearcher's factory.
factory FacetSearcher.create({
required String applicationID,
required String apiKey,
required FacetSearchState state,
Duration debounce = const Duration(milliseconds: 100),
ClientOptions? options,
}) =>
_FacetSearcher(
applicationID: applicationID,
apiKey: apiKey,
state: state,
debounce: debounce,
options: options,
);
/// Creates [FacetSearcher] using a custom [FacetSearchService].
@internal
factory FacetSearcher.custom(
FacetSearchService service,
FacetSearchState state, [
Duration debounce = const Duration(milliseconds: 100),
]) =>
_FacetSearcher.create(service, state, debounce);
/// Search state stream
Stream<FacetSearchState> get state;
/// Search results stream
Stream<FacetSearchResponse> get responses;
/// Set query string.
void query(String query);
/// Get current [FacetSearchState].
FacetSearchState snapshot();
/// Get latest [FacetSearchResponse].
FacetSearchResponse? get lastResponse;
/// Apply search state configuration.
void applyState(FacetSearchState Function(FacetSearchState state) config);
/// Re-run the last search query
void rerun();
}
/// Default implementation of [FacetSearcher].
class _FacetSearcher with DisposableMixin implements FacetSearcher {
/// FacetSearcher's factory.
factory _FacetSearcher({
required String applicationID,
required String apiKey,
required FacetSearchState state,
Duration debounce = const Duration(milliseconds: 100),
ClientOptions? options,
}) {
final service = AlgoliaFacetSearchService(
applicationID: applicationID,
apiKey: apiKey,
options: options,
);
return _FacetSearcher.create(
service,
state,
debounce,
);
}
/// FacetSearcher's constructor, for internal and test use only.
_FacetSearcher.create(
FacetSearchService searchService,
FacetSearchState state, [
Duration debounce = const Duration(milliseconds: 100),
]) : this._(
searchService,
BehaviorSubject.seeded(SearchRequest(state)),
debounce,
);
/// FacetSearcher's private constructor
_FacetSearcher._(
this.searchService,
this._request,
this.debounce,
) {
_subscriptions.add(_responses.connect());
}
/// Search state stream
@override
Stream<FacetSearchState> get state =>
_request.stream.map((request) => request.state);
/// Search results stream
@override
Stream<FacetSearchResponse> get responses => _responses;
/// Service handling search requests
final FacetSearchService searchService;
/// Search state debounce duration
final Duration debounce;
/// Search state subject
final BehaviorSubject<SearchRequest<FacetSearchState>> _request;
/// Search responses subject
late final _responses = _request.stream
.debounceTime(debounce)
.distinct()
.switchMap((req) => Stream.fromFuture(searchService.search(req.state)))
.doOnData((value) {
lastResponse = value;
}).publish();
/// Events logger
final Logger _log = algoliaLogger('FacetSearcher');
/// Streams subscriptions composite.
final CompositeSubscription _subscriptions = CompositeSubscription();
@override
void query(String query) {
applyState((state) => state.copyWith(facetQuery: query));
}
@override
FacetSearchState snapshot() => _request.value.state;
/// Get latest search response
@override
FacetSearchResponse? lastResponse;
/// Apply search state configuration.
@override
void applyState(FacetSearchState Function(FacetSearchState state) config) {
_updateState((state) => config(state));
}
/// Apply changes to the current state
void _updateState(FacetSearchState Function(FacetSearchState 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('FacetSearcher disposed');
_request.close();
_subscriptions.dispose();
}
}