-
Notifications
You must be signed in to change notification settings - Fork 215
/
searchClient.ts
3188 lines (2852 loc) · 112 KB
/
searchClient.ts
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
import {
createAuth,
createTransporter,
getAlgoliaAgent,
shuffle,
createIterablePromise,
} from '@algolia/client-common';
import type {
CreateClientOptions,
Headers,
Host,
QueryParameters,
Request,
RequestOptions,
ApiError,
IterableOptions,
} from '@algolia/client-common';
import type { AddApiKeyResponse } from '../model/addApiKeyResponse';
import type { ApiKey } from '../model/apiKey';
import type { BatchParams } from '../model/batchParams';
import type { BatchRequest } from '../model/batchRequest';
import type { BatchResponse } from '../model/batchResponse';
import type { BrowseResponse } from '../model/browseResponse';
import type {
BrowseOptions,
ChunkedBatchOptions,
ReplaceAllObjectsOptions,
ReplaceAllObjectsResponse,
WaitForApiKeyOptions,
WaitForTaskOptions,
AddOrUpdateObjectProps,
AssignUserIdProps,
BatchProps,
BatchAssignUserIdsProps,
BatchDictionaryEntriesProps,
BrowseProps,
ClearObjectsProps,
ClearRulesProps,
ClearSynonymsProps,
CustomDeleteProps,
CustomGetProps,
CustomPostProps,
CustomPutProps,
DeleteApiKeyProps,
DeleteByProps,
DeleteIndexProps,
DeleteObjectProps,
DeleteRuleProps,
DeleteSourceProps,
DeleteSynonymProps,
GetApiKeyProps,
GetLogsProps,
GetObjectProps,
GetRuleProps,
GetSettingsProps,
GetSynonymProps,
GetTaskProps,
GetUserIdProps,
HasPendingMappingsProps,
ListIndicesProps,
ListUserIdsProps,
OperationIndexProps,
PartialUpdateObjectProps,
RemoveUserIdProps,
ReplaceSourcesProps,
RestoreApiKeyProps,
SaveObjectProps,
SaveRuleProps,
SaveRulesProps,
SaveSynonymProps,
SaveSynonymsProps,
LegacySearchMethodProps,
SearchDictionaryEntriesProps,
SearchForFacetValuesProps,
SearchRulesProps,
SearchSingleIndexProps,
SearchSynonymsProps,
SetSettingsProps,
UpdateApiKeyProps,
} from '../model/clientMethodProps';
import type { CreatedAtResponse } from '../model/createdAtResponse';
import type { DeleteApiKeyResponse } from '../model/deleteApiKeyResponse';
import type { DeleteSourceResponse } from '../model/deleteSourceResponse';
import type { DeletedAtResponse } from '../model/deletedAtResponse';
import type { DictionarySettingsParams } from '../model/dictionarySettingsParams';
import type { GetApiKeyResponse } from '../model/getApiKeyResponse';
import type { GetDictionarySettingsResponse } from '../model/getDictionarySettingsResponse';
import type { GetLogsResponse } from '../model/getLogsResponse';
import type { GetObjectsParams } from '../model/getObjectsParams';
import type { GetObjectsResponse } from '../model/getObjectsResponse';
import type { GetTaskResponse } from '../model/getTaskResponse';
import type { GetTopUserIdsResponse } from '../model/getTopUserIdsResponse';
import type { HasPendingMappingsResponse } from '../model/hasPendingMappingsResponse';
import type { IndexSettings } from '../model/indexSettings';
import type { Languages } from '../model/languages';
import type { ListApiKeysResponse } from '../model/listApiKeysResponse';
import type { ListClustersResponse } from '../model/listClustersResponse';
import type { ListIndicesResponse } from '../model/listIndicesResponse';
import type { ListUserIdsResponse } from '../model/listUserIdsResponse';
import type { MultipleBatchResponse } from '../model/multipleBatchResponse';
import type { RemoveUserIdResponse } from '../model/removeUserIdResponse';
import type { ReplaceSourceResponse } from '../model/replaceSourceResponse';
import type { Rule } from '../model/rule';
import type { SaveObjectResponse } from '../model/saveObjectResponse';
import type { SaveSynonymResponse } from '../model/saveSynonymResponse';
import type { SearchDictionaryEntriesResponse } from '../model/searchDictionaryEntriesResponse';
import type { SearchForFacetValuesResponse } from '../model/searchForFacetValuesResponse';
import type { SearchMethodParams } from '../model/searchMethodParams';
import type { SearchResponse } from '../model/searchResponse';
import type { SearchResponses } from '../model/searchResponses';
import type { SearchRulesResponse } from '../model/searchRulesResponse';
import type { SearchSynonymsResponse } from '../model/searchSynonymsResponse';
import type { SearchUserIdsParams } from '../model/searchUserIdsParams';
import type { SearchUserIdsResponse } from '../model/searchUserIdsResponse';
import type { Source } from '../model/source';
import type { SynonymHit } from '../model/synonymHit';
import type { UpdateApiKeyResponse } from '../model/updateApiKeyResponse';
import type { UpdatedAtResponse } from '../model/updatedAtResponse';
import type { UpdatedAtWithObjectIdResponse } from '../model/updatedAtWithObjectIdResponse';
import type { UpdatedRuleResponse } from '../model/updatedRuleResponse';
import type { UserId } from '../model/userId';
export const apiClientVersion = '5.0.0-alpha.112';
function getDefaultHosts(appId: string): Host[] {
return (
[
{
url: `${appId}-dsn.algolia.net`,
accept: 'read',
protocol: 'https',
},
{
url: `${appId}.algolia.net`,
accept: 'write',
protocol: 'https',
},
] as Host[]
).concat(
shuffle([
{
url: `${appId}-1.algolianet.com`,
accept: 'readWrite',
protocol: 'https',
},
{
url: `${appId}-2.algolianet.com`,
accept: 'readWrite',
protocol: 'https',
},
{
url: `${appId}-3.algolianet.com`,
accept: 'readWrite',
protocol: 'https',
},
])
);
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createSearchClient({
appId: appIdOption,
apiKey: apiKeyOption,
authMode,
algoliaAgents,
...options
}: CreateClientOptions) {
const auth = createAuth(appIdOption, apiKeyOption, authMode);
const transporter = createTransporter({
hosts: getDefaultHosts(appIdOption),
...options,
algoliaAgent: getAlgoliaAgent({
algoliaAgents,
client: 'Search',
version: apiClientVersion,
}),
baseHeaders: {
'content-type': 'text/plain',
...auth.headers(),
...options.baseHeaders,
},
baseQueryParameters: {
...auth.queryParameters(),
...options.baseQueryParameters,
},
});
return {
transporter,
/**
* The `appId` currently in use.
*/
appId: appIdOption,
/**
* Clears the cache of the transporter for the `requestsCache` and `responsesCache` properties.
*/
clearCache(): Promise<void> {
return Promise.all([
transporter.requestsCache.clear(),
transporter.responsesCache.clear(),
]).then(() => undefined);
},
/**
* Get the value of the `algoliaAgent`, used by our libraries internally and telemetry system.
*/
get _ua(): string {
return transporter.algoliaAgent.value;
},
/**
* Adds a `segment` to the `x-algolia-agent` sent with every requests.
*
* @param segment - The algolia agent (user-agent) segment to add.
* @param version - The version of the agent.
*/
addAlgoliaAgent(segment: string, version?: string): void {
transporter.algoliaAgent.add({ segment, version });
},
/**
* Helper: Wait for a task to be published (completed) for a given `indexName` and `taskID`.
*
* @summary Helper method that waits for a task to be published (completed).
* @param waitForTaskOptions - The `waitForTaskOptions` object.
* @param waitForTaskOptions.indexName - The `indexName` where the operation was performed.
* @param waitForTaskOptions.taskID - The `taskID` returned in the method response.
* @param waitForTaskOptions.maxRetries - The maximum number of retries. 50 by default.
* @param waitForTaskOptions.timeout - The function to decide how long to wait between retries.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `getTask` method and merged with the transporter requestOptions.
*/
waitForTask(
{
indexName,
taskID,
maxRetries = 50,
timeout = (retryCount: number): number =>
Math.min(retryCount * 200, 5000),
}: WaitForTaskOptions,
requestOptions?: RequestOptions
): Promise<GetTaskResponse> {
let retryCount = 0;
return createIterablePromise({
func: () => this.getTask({ indexName, taskID }, requestOptions),
validate: (response) => response.status === 'published',
aggregator: () => (retryCount += 1),
error: {
validate: () => retryCount >= maxRetries,
message: () =>
`The maximum number of retries exceeded. (${retryCount}/${maxRetries})`,
},
timeout: () => timeout(retryCount),
});
},
/**
* Helper: Wait for an API key to be added, updated or deleted based on a given `operation`.
*
* @summary Helper method that waits for an API key task to be processed.
* @param waitForApiKeyOptions - The `waitForApiKeyOptions` object.
* @param waitForApiKeyOptions.operation - The `operation` that was done on a `key`.
* @param waitForApiKeyOptions.key - The `key` that has been added, deleted or updated.
* @param waitForApiKeyOptions.apiKey - Necessary to know if an `update` operation has been processed, compare fields of the response with it.
* @param waitForApiKeyOptions.maxRetries - The maximum number of retries. 50 by default.
* @param waitForApiKeyOptions.timeout - The function to decide how long to wait between retries.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `getApikey` method and merged with the transporter requestOptions.
*/
waitForApiKey(
{
operation,
key,
apiKey,
maxRetries = 50,
timeout = (retryCount: number): number =>
Math.min(retryCount * 200, 5000),
}: WaitForApiKeyOptions,
requestOptions?: RequestOptions
): Promise<ApiError | GetApiKeyResponse> {
let retryCount = 0;
const baseIteratorOptions: IterableOptions<ApiError | GetApiKeyResponse> =
{
aggregator: () => (retryCount += 1),
error: {
validate: () => retryCount >= maxRetries,
message: () =>
`The maximum number of retries exceeded. (${retryCount}/${maxRetries})`,
},
timeout: () => timeout(retryCount),
};
if (operation === 'update') {
if (!apiKey) {
throw new Error(
'`apiKey` is required when waiting for an `update` operation.'
);
}
return createIterablePromise({
...baseIteratorOptions,
func: () => this.getApiKey({ key }, requestOptions),
validate: (response) => {
for (const field of Object.keys(apiKey)) {
const value = apiKey[field as keyof ApiKey];
const resValue = response[field as keyof ApiKey];
if (Array.isArray(value) && Array.isArray(resValue)) {
if (
value.length !== resValue.length ||
value.some((v, index) => v !== resValue[index])
) {
return false;
}
} else if (value !== resValue) {
return false;
}
}
return true;
},
});
}
return createIterablePromise({
...baseIteratorOptions,
func: () =>
this.getApiKey({ key }, requestOptions).catch((error) => error),
validate: (error: ApiError) =>
operation === 'add' ? error.status !== 404 : error.status === 404,
});
},
/**
* Helper: Iterate on the `browse` method of the client to allow aggregating objects of an index.
*
* @summary Helper method that iterates on the `browse` method.
* @param browseObjects - The `browseObjects` object.
* @param browseObjects.indexName - The index in which to perform the request.
* @param browseObjects.browseParams - The `browse` parameters.
* @param browseObjects.validate - The validator function. It receive the resolved return of the API call. By default, stops when there is no `cursor` in the response.
* @param browseObjects.aggregator - The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `browse` method and merged with the transporter requestOptions.
*/
browseObjects<T>(
{
indexName,
browseParams,
...browseObjectsOptions
}: BrowseOptions<BrowseResponse<T>> & BrowseProps,
requestOptions?: RequestOptions
): Promise<BrowseResponse<T>> {
return createIterablePromise<BrowseResponse<T>>({
func: (previousResponse) => {
return this.browse(
{
indexName,
browseParams: {
cursor: previousResponse ? previousResponse.cursor : undefined,
...browseParams,
},
},
requestOptions
);
},
validate: (response) => response.cursor === undefined,
...browseObjectsOptions,
});
},
/**
* Helper: Iterate on the `searchRules` method of the client to allow aggregating rules of an index.
*
* @summary Helper method that iterates on the `searchRules` method.
* @param browseRules - The `browseRules` object.
* @param browseRules.indexName - The index in which to perform the request.
* @param browseRules.searchRulesParams - The `searchRules` method parameters.
* @param browseRules.validate - The validator function. It receive the resolved return of the API call. By default, stops when there is less hits returned than the number of maximum hits (1000).
* @param browseRules.aggregator - The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `searchRules` method and merged with the transporter requestOptions.
*/
browseRules(
{
indexName,
searchRulesParams,
...browseRulesOptions
}: BrowseOptions<SearchRulesResponse> & SearchRulesProps,
requestOptions?: RequestOptions
): Promise<SearchRulesResponse> {
const params = {
hitsPerPage: 1000,
...searchRulesParams,
};
return createIterablePromise<SearchRulesResponse>({
func: (previousResponse) => {
return this.searchRules(
{
indexName,
searchRulesParams: {
...params,
page: previousResponse
? previousResponse.page + 1
: params.page || 0,
},
},
requestOptions
);
},
validate: (response) => response.nbHits < params.hitsPerPage,
...browseRulesOptions,
});
},
/**
* Helper: Iterate on the `searchSynonyms` method of the client to allow aggregating rules of an index.
*
* @summary Helper method that iterates on the `searchSynonyms` method.
* @param browseSynonyms - The `browseSynonyms` object.
* @param browseSynonyms.indexName - The index in which to perform the request.
* @param browseSynonyms.validate - The validator function. It receive the resolved return of the API call. By default, stops when there is less hits returned than the number of maximum hits (1000).
* @param browseSynonyms.aggregator - The function that runs right after the API call has been resolved, allows you to do anything with the response before `validate`.
* @param browseSynonyms.searchSynonymsParams - The `searchSynonyms` method parameters.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `searchSynonyms` method and merged with the transporter requestOptions.
*/
browseSynonyms(
{
indexName,
searchSynonymsParams,
...browseSynonymsOptions
}: BrowseOptions<SearchSynonymsResponse> & SearchSynonymsProps,
requestOptions?: RequestOptions
): Promise<SearchSynonymsResponse> {
const params = {
page: 0,
...searchSynonymsParams,
hitsPerPage: 1000,
};
return createIterablePromise<SearchSynonymsResponse>({
func: (_) => {
const resp = this.searchSynonyms(
{
indexName,
searchSynonymsParams: {
...params,
page: params.page,
},
},
requestOptions
);
params.page += 1;
return resp;
},
validate: (response) => response.nbHits < params.hitsPerPage,
...browseSynonymsOptions,
});
},
/**
* Helper: calls the `search` method but with certainty that we will only request Algolia records (hits) and not facets.
* Disclaimer: We don't assert that the parameters you pass to this method only contains `hits` requests to prevent impacting search performances, this helper is purely for typing purposes.
*
* @summary Search multiple indices for `hits`.
* @param searchMethodParams - Query requests and strategies. Results will be received in the same order as the queries.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
searchForHits<T>(
searchMethodParams: LegacySearchMethodProps | SearchMethodParams,
requestOptions?: RequestOptions
): Promise<{ results: Array<SearchResponse<T>> }> {
return this.search(searchMethodParams, requestOptions) as Promise<{
results: Array<SearchResponse<T>>;
}>;
},
/**
* Helper: calls the `search` method but with certainty that we will only request Algolia facets and not records (hits).
* Disclaimer: We don't assert that the parameters you pass to this method only contains `facets` requests to prevent impacting search performances, this helper is purely for typing purposes.
*
* @summary Search multiple indices for `facets`.
* @param searchMethodParams - Query requests and strategies. Results will be received in the same order as the queries.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
searchForFacets(
searchMethodParams: LegacySearchMethodProps | SearchMethodParams,
requestOptions?: RequestOptions
): Promise<{ results: SearchForFacetValuesResponse[] }> {
return this.search(searchMethodParams, requestOptions) as Promise<{
results: SearchForFacetValuesResponse[];
}>;
},
/**
* Helper: Chunks the given `objects` list in subset of 1000 elements max in order to make it fit in `batch` requests.
*
* @summary Helper: Chunks the given `objects` list in subset of 1000 elements max in order to make it fit in `batch` requests.
* @param chunkedBatch - The `chunkedBatch` object.
* @param chunkedBatch.indexName - The `indexName` to replace `objects` in.
* @param chunkedBatch.objects - The array of `objects` to store in the given Algolia `indexName`.
* @param chunkedBatch.action - The `batch` `action` to perform on the given array of `objects`, defaults to `addObject`.
* @param chunkedBatch.waitForTasks - Whether or not we should wait until every `batch` tasks has been processed, this operation may slow the total execution time of this method but is more reliable.
* @param chunkedBatch.batchSize - The size of the chunk of `objects`. The number of `batch` calls will be equal to `length(objects) / batchSize`. Defaults to 1000.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `getTask` method and merged with the transporter requestOptions.
*/
async chunkedBatch(
{
indexName,
objects,
action = 'addObject',
waitForTasks,
batchSize = 1000,
}: ChunkedBatchOptions,
requestOptions?: RequestOptions
): Promise<BatchResponse[]> {
let requests: BatchRequest[] = [];
const responses: BatchResponse[] = [];
for (const [i, obj] of objects.entries()) {
requests.push({ action, body: obj });
if (i % batchSize === 0) {
responses.push(
await this.batch(
{ indexName, batchWriteParams: { requests } },
requestOptions
)
);
requests = [];
}
}
if (waitForTasks) {
for (const resp of responses) {
await this.waitForTask({ indexName, taskID: resp.taskID });
}
}
return responses;
},
/**
* Helper: Replaces all objects (records) in the given `index_name` with the given `objects`. A temporary index is created during this process in order to backup your data.
*
* @summary Helper: Replaces all objects (records) in the given `index_name` with the given `objects`. A temporary index is created during this process in order to backup your data.
* @param replaceAllObjects - The `replaceAllObjects` object.
* @param replaceAllObjects.indexName - The `indexName` to replace `objects` in.
* @param replaceAllObjects.objects - The array of `objects` to store in the given Algolia `indexName`.
* @param replaceAllObjects.batchSize - The size of the chunk of `objects`. The number of `batch` calls will be equal to `length(objects) / batchSize`. Defaults to 1000.
* @param requestOptions - The requestOptions to send along with the query, they will be forwarded to the `getTask` method and merged with the transporter requestOptions.
*/
async replaceAllObjects(
{ indexName, objects, batchSize }: ReplaceAllObjectsOptions,
requestOptions?: RequestOptions
): Promise<ReplaceAllObjectsResponse> {
const randomSuffix = Math.random().toString(36).substring(7);
const tmpIndexName = `${indexName}_tmp_${randomSuffix}`;
const copyOperationResponse = await this.operationIndex(
{
indexName,
operationIndexParams: {
operation: 'copy',
destination: tmpIndexName,
scope: ['settings', 'rules', 'synonyms'],
},
},
requestOptions
);
await this.waitForTask({
indexName,
taskID: copyOperationResponse.taskID,
});
const batchResponses = await this.chunkedBatch(
{ indexName: tmpIndexName, objects, waitForTasks: true, batchSize },
requestOptions
);
const moveOperationResponse = await this.operationIndex(
{
indexName: tmpIndexName,
operationIndexParams: { operation: 'move', destination: indexName },
},
requestOptions
);
await this.waitForTask({
indexName,
taskID: moveOperationResponse.taskID,
});
return { copyOperationResponse, batchResponses, moveOperationResponse };
},
/**
* Creates a new API key with specific permissions and restrictions.
*
* Required API Key ACLs:
* - admin.
*
* @param apiKey - The apiKey object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addApiKey(
apiKey: ApiKey,
requestOptions?: RequestOptions
): Promise<AddApiKeyResponse> {
if (!apiKey) {
throw new Error(
'Parameter `apiKey` is required when calling `addApiKey`.'
);
}
if (!apiKey.acl) {
throw new Error(
'Parameter `apiKey.acl` is required when calling `addApiKey`.'
);
}
const requestPath = '/1/keys';
const headers: Headers = {};
const queryParameters: QueryParameters = {};
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: apiKey,
};
return transporter.request(request, requestOptions);
},
/**
* If a record with the specified object ID exists, the existing record is replaced. Otherwise, a new record is added to the index. To update _some_ attributes of an existing record, use the [`partial` operation](#tag/Records/operation/partialUpdateObject) instead. To add, update, or replace multiple records, use the [`batch` operation](#tag/Records/operation/batch).
*
* Required API Key ACLs:
* - addObject.
*
* @param addOrUpdateObject - The addOrUpdateObject object.
* @param addOrUpdateObject.indexName - Name of the index on which to perform the operation.
* @param addOrUpdateObject.objectID - Unique record identifier.
* @param addOrUpdateObject.body - The record, a schemaless object with attributes that are useful in the context of search and discovery.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
addOrUpdateObject(
{ indexName, objectID, body }: AddOrUpdateObjectProps,
requestOptions?: RequestOptions
): Promise<UpdatedAtWithObjectIdResponse> {
if (!indexName) {
throw new Error(
'Parameter `indexName` is required when calling `addOrUpdateObject`.'
);
}
if (!objectID) {
throw new Error(
'Parameter `objectID` is required when calling `addOrUpdateObject`.'
);
}
if (!body) {
throw new Error(
'Parameter `body` is required when calling `addOrUpdateObject`.'
);
}
const requestPath = '/1/indexes/{indexName}/{objectID}'
.replace('{indexName}', encodeURIComponent(indexName))
.replace('{objectID}', encodeURIComponent(objectID));
const headers: Headers = {};
const queryParameters: QueryParameters = {};
const request: Request = {
method: 'PUT',
path: requestPath,
queryParameters,
headers,
data: body,
};
return transporter.request(request, requestOptions);
},
/**
* Adds a source to the list of allowed sources.
*
* Required API Key ACLs:
* - admin.
*
* @param source - Source to add.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
appendSource(
source: Source,
requestOptions?: RequestOptions
): Promise<CreatedAtResponse> {
if (!source) {
throw new Error(
'Parameter `source` is required when calling `appendSource`.'
);
}
if (!source.source) {
throw new Error(
'Parameter `source.source` is required when calling `appendSource`.'
);
}
const requestPath = '/1/security/sources/append';
const headers: Headers = {};
const queryParameters: QueryParameters = {};
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: source,
};
return transporter.request(request, requestOptions);
},
/**
* Assigns or moves a user ID to a cluster. The time it takes to move a user is proportional to the amount of data linked to the user ID.
*
* Required API Key ACLs:
* - admin.
*
* @param assignUserId - The assignUserId object.
* @param assignUserId.xAlgoliaUserID - Unique identifier of the user who makes the search request.
* @param assignUserId.assignUserIdParams - The assignUserIdParams object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
assignUserId(
{ xAlgoliaUserID, assignUserIdParams }: AssignUserIdProps,
requestOptions?: RequestOptions
): Promise<CreatedAtResponse> {
if (!xAlgoliaUserID) {
throw new Error(
'Parameter `xAlgoliaUserID` is required when calling `assignUserId`.'
);
}
if (!assignUserIdParams) {
throw new Error(
'Parameter `assignUserIdParams` is required when calling `assignUserId`.'
);
}
if (!assignUserIdParams.cluster) {
throw new Error(
'Parameter `assignUserIdParams.cluster` is required when calling `assignUserId`.'
);
}
const requestPath = '/1/clusters/mapping';
const headers: Headers = {};
const queryParameters: QueryParameters = {};
if (xAlgoliaUserID !== undefined) {
headers['X-Algolia-User-ID'] = xAlgoliaUserID.toString();
}
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: assignUserIdParams,
};
return transporter.request(request, requestOptions);
},
/**
* Adds, updates, or deletes records in one index with a single API request. Batching index updates reduces latency and increases data integrity. - Actions are applied in the order they\'re specified. - Actions are equivalent to the individual API requests of the same name.
*
* @param batch - The batch object.
* @param batch.indexName - Name of the index on which to perform the operation.
* @param batch.batchWriteParams - The batchWriteParams object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
batch(
{ indexName, batchWriteParams }: BatchProps,
requestOptions?: RequestOptions
): Promise<BatchResponse> {
if (!indexName) {
throw new Error(
'Parameter `indexName` is required when calling `batch`.'
);
}
if (!batchWriteParams) {
throw new Error(
'Parameter `batchWriteParams` is required when calling `batch`.'
);
}
if (!batchWriteParams.requests) {
throw new Error(
'Parameter `batchWriteParams.requests` is required when calling `batch`.'
);
}
const requestPath = '/1/indexes/{indexName}/batch'.replace(
'{indexName}',
encodeURIComponent(indexName)
);
const headers: Headers = {};
const queryParameters: QueryParameters = {};
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: batchWriteParams,
};
return transporter.request(request, requestOptions);
},
/**
* Assigns multiple user IDs to a cluster. **You can\'t move users with this operation**.
*
* Required API Key ACLs:
* - admin.
*
* @param batchAssignUserIds - The batchAssignUserIds object.
* @param batchAssignUserIds.xAlgoliaUserID - Unique identifier of the user who makes the search request.
* @param batchAssignUserIds.batchAssignUserIdsParams - The batchAssignUserIdsParams object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
batchAssignUserIds(
{ xAlgoliaUserID, batchAssignUserIdsParams }: BatchAssignUserIdsProps,
requestOptions?: RequestOptions
): Promise<CreatedAtResponse> {
if (!xAlgoliaUserID) {
throw new Error(
'Parameter `xAlgoliaUserID` is required when calling `batchAssignUserIds`.'
);
}
if (!batchAssignUserIdsParams) {
throw new Error(
'Parameter `batchAssignUserIdsParams` is required when calling `batchAssignUserIds`.'
);
}
if (!batchAssignUserIdsParams.cluster) {
throw new Error(
'Parameter `batchAssignUserIdsParams.cluster` is required when calling `batchAssignUserIds`.'
);
}
if (!batchAssignUserIdsParams.users) {
throw new Error(
'Parameter `batchAssignUserIdsParams.users` is required when calling `batchAssignUserIds`.'
);
}
const requestPath = '/1/clusters/mapping/batch';
const headers: Headers = {};
const queryParameters: QueryParameters = {};
if (xAlgoliaUserID !== undefined) {
headers['X-Algolia-User-ID'] = xAlgoliaUserID.toString();
}
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: batchAssignUserIdsParams,
};
return transporter.request(request, requestOptions);
},
/**
* Adds or deletes multiple entries from your plurals, segmentation, or stop word dictionaries.
*
* Required API Key ACLs:
* - editSettings.
*
* @param batchDictionaryEntries - The batchDictionaryEntries object.
* @param batchDictionaryEntries.dictionaryName - Dictionary type in which to search.
* @param batchDictionaryEntries.batchDictionaryEntriesParams - The batchDictionaryEntriesParams object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
batchDictionaryEntries(
{
dictionaryName,
batchDictionaryEntriesParams,
}: BatchDictionaryEntriesProps,
requestOptions?: RequestOptions
): Promise<UpdatedAtResponse> {
if (!dictionaryName) {
throw new Error(
'Parameter `dictionaryName` is required when calling `batchDictionaryEntries`.'
);
}
if (!batchDictionaryEntriesParams) {
throw new Error(
'Parameter `batchDictionaryEntriesParams` is required when calling `batchDictionaryEntries`.'
);
}
if (!batchDictionaryEntriesParams.requests) {
throw new Error(
'Parameter `batchDictionaryEntriesParams.requests` is required when calling `batchDictionaryEntries`.'
);
}
const requestPath = '/1/dictionaries/{dictionaryName}/batch'.replace(
'{dictionaryName}',
encodeURIComponent(dictionaryName)
);
const headers: Headers = {};
const queryParameters: QueryParameters = {};
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: batchDictionaryEntriesParams,
};
return transporter.request(request, requestOptions);
},
/**
* Retrieves records from an index, up to 1,000 per request. While searching retrieves _hits_ (records augmented with attributes for highlighting and ranking details), browsing _just_ returns matching records. This can be useful if you want to export your indices. - The Analytics API doesn\'t collect data when using `browse`. - Records are ranked by attributes and custom ranking. - Deduplication (`distinct`) is turned off. - There\'s no ranking for: typo-tolerance, number of matched words, proximity, geo distance.
*
* Required API Key ACLs:
* - browse.
*
* @param browse - The browse object.
* @param browse.indexName - Name of the index on which to perform the operation.
* @param browse.browseParams - The browseParams object.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
browse<T>(
{ indexName, browseParams }: BrowseProps,
requestOptions?: RequestOptions
): Promise<BrowseResponse<T>> {
if (!indexName) {
throw new Error(
'Parameter `indexName` is required when calling `browse`.'
);
}
const requestPath = '/1/indexes/{indexName}/browse'.replace(
'{indexName}',
encodeURIComponent(indexName)
);
const headers: Headers = {};
const queryParameters: QueryParameters = {};
const request: Request = {
method: 'POST',
path: requestPath,
queryParameters,
headers,
data: browseParams ? browseParams : {},
};
return transporter.request(request, requestOptions);
},
/**
* Deletes only the records from an index while keeping settings, synonyms, and rules.
*
* Required API Key ACLs:
* - deleteIndex.
*
* @param clearObjects - The clearObjects object.
* @param clearObjects.indexName - Name of the index on which to perform the operation.
* @param requestOptions - The requestOptions to send along with the query, they will be merged with the transporter requestOptions.
*/
clearObjects(
{ indexName }: ClearObjectsProps,
requestOptions?: RequestOptions
): Promise<UpdatedAtResponse> {
if (!indexName) {
throw new Error(
'Parameter `indexName` is required when calling `clearObjects`.'
);
}
const requestPath = '/1/indexes/{indexName}/clear'.replace(
'{indexName}',
encodeURIComponent(indexName)
);
const headers: Headers = {};