-
Notifications
You must be signed in to change notification settings - Fork 216
/
algoliasearch.js
1552 lines (1454 loc) · 69.8 KB
/
algoliasearch.js
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
/*
* Copyright (c) 2013 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Algolia Search library initialization
* @param applicationID the application ID you have in your admin interface
* @param apiKey a valid API key for the service
* @param methodOrOptions the hash of parameters for initialization. It can contains:
* - method (optional) specify if the protocol used is http or https (http by default to make the first search query faster).
* You need to use https is you are doing something else than just search queries.
* - hosts (optional) the list of hosts that you have received for the service
* - dsn (optional) set to true if your account has the Distributed Search Option
* - dsnHost (optional) override the automatic computation of dsn hostname
*/
var AlgoliaSearch = function(applicationID, apiKey, methodOrOptions, resolveDNS, hosts) {
var self = this;
this.applicationID = applicationID;
this.apiKey = apiKey;
this.dsn = true;
this.dsnHost = null;
this.hosts = [];
this.currentHostIndex = 0;
this.requestTimeoutInMs = 2000;
this.extraHeaders = [];
this.jsonp = null;
this.options = {};
// make sure every client instance has it's own cache
this.cache = {};
var method;
var tld = 'net';
if (typeof methodOrOptions === 'string') { // Old initialization
method = methodOrOptions;
} else {
// Take all option from the hash
var options = methodOrOptions || {};
this.options = options;
if (!this._isUndefined(options.method)) {
method = options.method;
}
if (!this._isUndefined(options.tld)) {
tld = options.tld;
}
if (!this._isUndefined(options.dsn)) {
this.dsn = options.dsn;
}
if (!this._isUndefined(options.hosts)) {
hosts = options.hosts;
}
if (!this._isUndefined(options.dsnHost)) {
this.dsnHost = options.dsnHost;
}
if (!this._isUndefined(options.requestTimeoutInMs)) {
this.requestTimeoutInMs = +options.requestTimeoutInMs;
}
if (!this._isUndefined(options.jsonp)) {
this.jsonp = options.jsonp;
}
}
// If hosts is undefined, initialize it with applicationID
if (this._isUndefined(hosts)) {
hosts = [
this.applicationID + '-1.algolia.' + tld,
this.applicationID + '-2.algolia.' + tld,
this.applicationID + '-3.algolia.' + tld
];
}
// detect is we use http or https
this.host_protocol = 'http://';
if (this._isUndefined(method) || method === null) {
this.host_protocol = ('https:' == document.location.protocol ? 'https' : 'http') + '://';
} else if (method === 'https' || method === 'HTTPS') {
this.host_protocol = 'https://';
}
// Add hosts in random order
for (var i = 0; i < hosts.length; ++i) {
if (Math.random() > 0.5) {
this.hosts.reverse();
}
this.hosts.push(this.host_protocol + hosts[i]);
}
if (Math.random() > 0.5) {
this.hosts.reverse();
}
// then add Distributed Search Network host if there is one
if (this.dsn || this.dsnHost != null) {
if (this.dsnHost) {
this.hosts.unshift(this.host_protocol + this.dsnHost);
} else {
this.hosts.unshift(this.host_protocol + this.applicationID + '-dsn.algolia.' + tld);
}
}
// angular dependencies injection
if (this.options.angular) {
this.options.angular.$injector.invoke(['$http', '$q', function ($http, $q) {
self.options.angular.$q = $q;
self.options.angular.$http = $http;
}]);
}
};
// This holds the number of JSONP requests done accross clients
// It's used as part of the ?callback=JSONP_$JSONPCounter when we do JSONP requests
AlgoliaSearch.JSONPCounter = 0;
function AlgoliaExplainResults(hit, titleAttribute, otherAttributes) {
function _getHitExplanationForOneAttr_recurse(obj, foundWords) {
var res = [];
if (typeof obj === 'object' && 'matchedWords' in obj && 'value' in obj) {
var match = false;
for (var j = 0; j < obj.matchedWords.length; ++j) {
var word = obj.matchedWords[j];
if (!(word in foundWords)) {
foundWords[word] = 1;
match = true;
}
}
if (match) {
res.push(obj.value);
}
} else if (Object.prototype.toString.call(obj) === '[object Array]') {
for (var i = 0; i < obj.length; ++i) {
var array = _getHitExplanationForOneAttr_recurse(obj[i], foundWords);
res = res.concat(array);
}
} else if (typeof obj === 'object') {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)){
res = res.concat(_getHitExplanationForOneAttr_recurse(obj[prop], foundWords));
}
}
}
return res;
}
function _getHitExplanationForOneAttr(hit, foundWords, attr) {
var base = hit._highlightResult || hit;
if (attr.indexOf('.') === -1) {
if (attr in base) {
return _getHitExplanationForOneAttr_recurse(base[attr], foundWords);
}
return [];
}
var array = attr.split('.');
var obj = base;
for (var i = 0; i < array.length; ++i) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
var res = [];
for (var j = 0; j < obj.length; ++j) {
res = res.concat(_getHitExplanationForOneAttr(obj[j], foundWords, array.slice(i).join('.')));
}
return res;
}
if (array[i] in obj) {
obj = obj[array[i]];
} else {
return [];
}
}
return _getHitExplanationForOneAttr_recurse(obj, foundWords);
}
var res = {};
var foundWords = {};
var title = _getHitExplanationForOneAttr(hit, foundWords, titleAttribute);
res.title = (title.length > 0) ? title[0] : '';
res.subtitles = [];
if (typeof otherAttributes !== 'undefined') {
for (var i = 0; i < otherAttributes.length; ++i) {
var attr = _getHitExplanationForOneAttr(hit, foundWords, otherAttributes[i]);
for (var j = 0; j < attr.length; ++j) {
res.subtitles.push({ attr: otherAttributes[i], value: attr[j] });
}
}
}
return res;
}
AlgoliaSearch.prototype = {
/*
* Delete an index
*
* @param indexName the name of index to delete
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
deleteIndex: function(indexName, callback) {
return this._jsonRequest({ method: 'DELETE',
url: '/1/indexes/' + encodeURIComponent(indexName),
callback: callback });
},
/**
* Move an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
moveIndex: function(srcIndexName, dstIndexName, callback) {
var postObj = {operation: 'move', destination: dstIndexName};
return this._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
callback: callback });
},
/**
* Copy an existing index.
* @param srcIndexName the name of index to copy.
* @param dstIndexName the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist).
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
copyIndex: function(srcIndexName, dstIndexName, callback) {
var postObj = {operation: 'copy', destination: dstIndexName};
return this._jsonRequest({ method: 'POST',
url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation',
body: postObj,
callback: callback });
},
/**
* Return last log entries.
* @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
* @param length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000.
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer that contains the task ID
*/
getLogs: function(callback, offset, length) {
if (this._isUndefined(offset)) {
offset = 0;
}
if (this._isUndefined(length)) {
length = 10;
}
return this._jsonRequest({ method: 'GET',
url: '/1/logs?offset=' + offset + '&length=' + length,
callback: callback });
},
/*
* List all existing indexes (paginated)
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with index list or error description if success is false.
* @param page The page to retrieve, starting at 0.
*/
listIndexes: function(callback, page) {
var params = typeof page !== 'undefined' ? '?page=' + page : '';
return this._jsonRequest({ method: 'GET',
url: '/1/indexes' + params,
callback: callback });
},
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
initIndex: function(indexName) {
return new this.Index(this, indexName);
},
/*
* List all existing user keys with their associated ACLs
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
listUserKeys: function(callback) {
return this._jsonRequest({ method: 'GET',
url: '/1/keys',
callback: callback });
},
/*
* Get ACL of a user key
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
getUserKeyACL: function(key, callback) {
return this._jsonRequest({ method: 'GET',
url: '/1/keys/' + key,
callback: callback });
},
/*
* Delete an existing user key
*
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
deleteUserKey: function(key, callback) {
return this._jsonRequest({ method: 'DELETE',
url: '/1/keys/' + key,
callback: callback });
},
/*
* Add an existing user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
addUserKey: function(acls, callback) {
return this.addUserKeyWithValidity(acls, 0, 0, 0, callback);
},
/*
* Add an existing user key
*
* @param acls the list of ACL for this key. Defined by an array of strings that
* can contains the following values:
* - search: allow to search (https and http)
* - addObject: allows to add/update an object in the index (https only)
* - deleteObject : allows to delete an existing object (https only)
* - deleteIndex : allows to delete index content (https only)
* - settings : allows to get index settings (https only)
* - editSettings : allows to change index settings (https only)
* @param validity the number of seconds after which the key will be automatically removed (0 means no time limit for this key)
* @param maxQueriesPerIPPerHour Specify the maximum number of API calls allowed from an IP address per hour.
* @param maxHitsPerQuery Specify the maximum number of hits this API key can retrieve in one call.
* @param callback the result callback with two arguments
* success: boolean set to true if the request was successfull
* content: the server answer with user keys list or error description if success is false.
*/
addUserKeyWithValidity: function(acls, validity, maxQueriesPerIPPerHour, maxHitsPerQuery, callback) {
var aclsObject = {};
aclsObject.acl = acls;
aclsObject.validity = validity;
aclsObject.maxQueriesPerIPPerHour = maxQueriesPerIPPerHour;
aclsObject.maxHitsPerQuery = maxHitsPerQuery;
return this._jsonRequest({ method: 'POST',
url: '/1/keys',
body: aclsObject,
callback: callback });
},
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
setSecurityTags: function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.tagFilters = tags;
},
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
setUserToken: function(userToken) {
this.userToken = userToken;
},
/*
* Initialize a new batch of search queries
*/
startQueriesBatch: function() {
this.batch = [];
},
/*
* Add a search query in the batch
*
* @param query the full text query
* @param args (optional) if set, contains an object with query parameters:
* - attributes: an array of object attribute names to retrieve
* (if not set all attributes are retrieve)
* - attributesToHighlight: an array of object attribute names to highlight
* (if not set indexed attributes are highlighted)
* - minWordSizefor1Typo: the minimum number of characters to accept one typo.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters to accept two typos.
* Defaults to 7.
* - getRankingInfo: if set, the result hits will contain ranking information in
* _rankingInfo attribute
* - page: (pagination parameter) page to retrieve (zero base). Defaults to 0.
* - hitsPerPage: (pagination parameter) number of hits per page. Defaults to 10.
*/
addQueryInBatch: function(indexName, query, args) {
var params = 'query=' + encodeURIComponent(query);
if (!this._isUndefined(args) && args !== null) {
params = this._getSearchParams(args, params);
}
this.batch.push({ indexName: indexName, params: params });
},
/*
* Clear all queries in cache
*/
clearCache: function() {
this.cache = {};
},
/*
* Launch the batch of queries using XMLHttpRequest.
* (Optimized for browser using a POST query to minimize number of OPTIONS queries)
*
* @param callback the function that will receive results
* @param delay (optional) if set, wait for this delay (in ms) and only send the batch if there was no other in the meantime.
*/
sendQueriesBatch: function(callback, delay) {
var as = this;
var params = {requests: []};
for (var i = 0; i < as.batch.length; ++i) {
params.requests.push(as.batch[i]);
}
window.clearTimeout(as.onDelayTrigger);
if (!this._isUndefined(delay) && delay !== null && delay > 0) {
var onDelayTrigger = window.setTimeout( function() {
as._sendQueriesBatch(params, callback);
}, delay);
as.onDelayTrigger = onDelayTrigger;
} else {
return this._sendQueriesBatch(params, callback);
}
},
/**
* Set the number of milliseconds a request can take before automatically being terminated.
*
* @param {Number} milliseconds
*/
setRequestTimeout: function(milliseconds)
{
if (milliseconds) {
this.requestTimeoutInMs = parseInt(milliseconds, 10);
}
},
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
Index: function(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
},
/**
* Add an extra field to the HTTP request
*
* @param key the header field name
* @param value the header field value
*/
setExtraHeader: function(key, value) {
this.extraHeaders.push({ key: key, value: value});
},
_sendQueriesBatch: function(params, callback) {
if (this.jsonp === null) {
var self = this;
return this._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/indexes/*/queries',
body: params,
callback: function(success, content) {
if (!success) {
// retry first with JSONP
self.jsonp = true;
self._sendQueriesBatch(params, callback);
} else {
self.jsonp = false;
callback && callback(success, content);
}
}
});
} else if (this.jsonp) {
var jsonpParams = '';
for (var i = 0; i < params.requests.length; ++i) {
var q = '/1/indexes/' + encodeURIComponent(params.requests[i].indexName) + '?' + params.requests[i].params;
jsonpParams += i + '=' + encodeURIComponent(q) + '&';
}
var pObj = {params: jsonpParams};
return this._jsonRequest({ cache: this.cache,
method: 'GET',
url: '/1/indexes/*',
body: pObj,
callback: callback });
} else {
return this._jsonRequest({ cache: this.cache,
method: 'POST',
url: '/1/indexes/*/queries',
body: params,
callback: callback});
}
},
/*
* Wrapper that try all hosts to maximize the quality of service
*/
_jsonRequest: function(opts) {
var self = this;
var callback = opts.callback;
var cache = null;
var cacheID = opts.url;
var deferred = null;
if (this.options.jQuery) {
deferred = this.options.jQuery.$.Deferred();
deferred.promise = deferred.promise(); // promise is a property in angular
} else if (this.options.angular) {
deferred = this.options.angular.$q.defer();
}
if (!this._isUndefined(opts.body)) {
cacheID = opts.url + '_body_' + JSON.stringify(opts.body);
}
if (!this._isUndefined(opts.cache)) {
cache = opts.cache;
if (!this._isUndefined(cache[cacheID])) {
if (!this._isUndefined(callback) && callback) {
setTimeout(function () { callback(true, cache[cacheID]); }, 1);
}
deferred && deferred.resolve(cache[cacheID]);
return deferred && deferred.promise;
}
}
opts.successiveRetryCount = 0;
var impl = function() {
if (opts.successiveRetryCount >= self.hosts.length) {
var error = { message: 'Cannot connect the Algolia\'s Search API. Please send an email to support@algolia.com to report the issue.' };
if (!self._isUndefined(callback) && callback) {
opts.successiveRetryCount = 0;
callback(false, error);
}
deferred && deferred.reject(error);
return;
}
opts.callback = function(retry, success, obj, body) {
if (success && !self._isUndefined(opts.cache)) {
cache[cacheID] = body;
}
if (!success && retry) {
self.currentHostIndex = ++self.currentHostIndex % self.hosts.length;
opts.successiveRetryCount += 1;
impl();
} else {
opts.successiveRetryCount = 0;
deferred && (success ? deferred.resolve(body) : deferred.reject(body));
if (!self._isUndefined(callback) && callback) {
callback(success, body);
}
}
};
opts.hostname = self.hosts[self.currentHostIndex];
self._jsonRequestByHost(opts);
};
impl();
return deferred && deferred.promise;
},
_jsonRequestByHost: function(opts) {
var self = this;
var url = opts.hostname + opts.url;
if (this.jsonp) {
this._makeJsonpRequestByHost(url, opts);
} else if (this.options.jQuery) {
this._makejQueryRequestByHost(url, opts);
} else if (this.options.angular) {
this._makeAngularRequestByHost(url, opts);
} else {
this._makeXmlHttpRequestByHost(url, opts);
}
},
/**
* Make a $http
*
* @param url request url (includes endpoint and path)
* @param opts all request opts
*/
_makeAngularRequestByHost: function(url, opts) {
var self = this;
var body = null;
if (!this._isUndefined(opts.body)) {
body = JSON.stringify(opts.body);
}
url += ((url.indexOf('?') === -1) ? '?' : '&') + 'X-Algolia-API-Key=' + this.apiKey;
url += '&X-Algolia-Application-Id=' + this.applicationID;
if (this.userToken) {
url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken);
}
if (this.tagFilters) {
url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters);
}
for (var i = 0; i < this.extraHeaders.length; ++i) {
url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value;
}
this.options.angular.$http({
url: url,
method: opts.method,
data: body,
cache: false,
timeout: (this.requestTimeoutInMs * (opts.successiveRetryCount + 1))
}).then(function(response) {
opts.callback(false, true, null, response.data);
}, function(response) {
if (response.status === 0) {
// xhr.timeout is not handled by Angular.js right now
// let's retry
opts.callback(true, false, null, response.data);
} else if (response.status == 400 || response.status === 403 || response.status === 404) {
opts.callback(false, false, null, response.data);
} else {
opts.callback(true, false, null, response.data);
}
});
},
/**
* Make a $.ajax
*
* @param url request url (includes endpoint and path)
* @param opts all request opts
*/
_makejQueryRequestByHost: function(url, opts) {
var self = this;
var body = null;
if (!this._isUndefined(opts.body)) {
body = JSON.stringify(opts.body);
}
url += ((url.indexOf('?') === -1) ? '?' : '&') + 'X-Algolia-API-Key=' + this.apiKey;
url += '&X-Algolia-Application-Id=' + this.applicationID;
if (this.userToken) {
url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken);
}
if (this.tagFilters) {
url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters);
}
for (var i = 0; i < this.extraHeaders.length; ++i) {
url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value;
}
this.options.jQuery.$.ajax(url, {
type: opts.method,
timeout: (this.requestTimeoutInMs * (opts.successiveRetryCount + 1)),
dataType: 'json',
data: body,
error: function(xhr, textStatus, error) {
if (textStatus === 'timeout') {
opts.callback(true, false, null, { 'message': 'Timeout - Could not connect to endpoint ' + url } );
} else if (xhr.status === 400 || xhr.status === 403 || xhr.status === 404) {
opts.callback(false, false, null, xhr.responseJSON );
} else {
opts.callback(true, false, null, { 'message': error } );
}
},
success: function(data, textStatus, xhr) {
opts.callback(false, true, null, data);
}
});
},
/**
* Make a JSONP request
*
* @param url request url (includes endpoint and path)
* @param opts all request options
*/
_makeJsonpRequestByHost: function(url, opts) {
if (opts.method !== 'GET') {
opts.callback(true, false, null, { 'message': 'Method ' + opts.method + ' ' + url + ' is not supported by JSONP.' });
return;
}
var cbCalled = false;
var timedOut = false;
AlgoliaSearch.JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cb = 'algoliaJSONP_' + AlgoliaSearch.JSONPCounter;
var done = false;
var ontimeout;
var success;
var clean;
window[cb] = function(data) {
try { delete window[cb]; } catch (e) { window[cb] = undefined; }
if (timedOut) {
return;
}
var status =
data && data.message && data.status ||
data && 200;
var ok = status === 200;
var retry = !ok && status !== 400 && status !== 403 && status !== 404;
cbCalled = true;
opts.callback(retry, ok, null, data);
};
script.type = 'text/javascript';
url += '?callback=' + cb + '&X-Algolia-Application-Id=' + this.applicationID + '&X-Algolia-API-Key=' + this.apiKey;
if (this.tagFilters) {
url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters);
}
if (this.userToken) {
url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken);
}
for (var i = 0; i < this.extraHeaders.length; ++i) {
url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value;
}
if (opts.body && opts.body.params) {
url += '&' + opts.body.params;
}
ontimeout = setTimeout(function() {
timedOut = true;
clean();
opts.callback(true, false, null, { 'message': 'Timeout - Failed to load JSONP script.' });
}, this.requestTimeoutInMs);
success = function() {
if (done || timedOut) {
return;
}
done = true;
clean();
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' });
}
};
clean = function() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
try {
delete window[cb];
delete window[cb + '_loaded'];
} catch (e) {
window[cb] = null;
window[cb + '_loaded'] = null;
}
};
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
};
script.onload = function() {
success();
};
script.onerror = function() {
if (done || timedOut) {
return;
}
clean();
opts.callback(true, false, null, { 'message': 'Failed to load JSONP script.' });
};
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
},
/**
* Make a XmlHttpRequest
*
* @param url request url (includes endpoint and path)
* @param opts all request opts
*/
_makeXmlHttpRequestByHost: function(url, opts) {
// no cors or XDomainRequest, no request
if (!this._support.cors && !this._support.hasXDomainRequest) {
// very old browser, not supported
opts.callback(false, false, null, { 'message': 'CORS not supported' });
return;
}
var body = null;
var request = this._support.cors ? new XMLHttpRequest() : new XDomainRequest();
var ontimeout;
var self = this;
var timedOut;
var timeoutListener;
if (!this._isUndefined(opts.body)) {
body = JSON.stringify(opts.body);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + 'X-Algolia-API-Key=' + this.apiKey;
url += '&X-Algolia-Application-Id=' + this.applicationID;
if (this.userToken) {
url += '&X-Algolia-UserToken=' + encodeURIComponent(this.userToken);
}
if (this.tagFilters) {
url += '&X-Algolia-TagFilters=' + encodeURIComponent(this.tagFilters);
}
for (var i = 0; i < this.extraHeaders.length; ++i) {
url += '&' + this.extraHeaders[i].key + '=' + this.extraHeaders[i].value;
}
timeoutListener = function() {
if (!self._support.timeout) {
timedOut = true;
request.abort();
}
opts.callback(true, false, null, { 'message': 'Timeout - Could not connect to endpoint ' + url } );
};
request.open(opts.method, url);
if (this._support.cors && body !== null && opts.method !== 'GET') {
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
request.onload = function(event) {
// When browser does not supports request.timeout, we can
// have both a load and timeout event
if (timedOut) {
return;
}
if (!self._support.timeout) {
clearTimeout(ontimeout);
}
var response = null;
try {
response = JSON.parse(request.responseText);
} catch(e) {}
var status =
// XHR provides a `status` property
request.status ||
// XDR does not have a `status` property,
// we rely on our own API response `status`, only
// provided when an error occurs, so we expect a .message
response && response.message && response.status ||
// XDR default to success when no response.status
response && 200;
var success = status === 200 || status === 201;
var retry = !success && status !== 400 && status !== 403 && status !== 404;
opts.callback(retry, success, event.target, response);
};
if (this._support.timeout) {
// .timeout supported by both XHR and XDR,
// we do receive timeout event, tested
request.timeout = this.requestTimeoutInMs * (opts.successiveRetryCount + 1);
request.ontimeout = timeoutListener;
} else {
ontimeout = setTimeout(timeoutListener, this.requestTimeoutInMs * (opts.successiveRetryCount + 1));
}
request.onerror = function(event) {
if (timedOut) {
return;
}
if (!self._support.timeout) {
clearTimeout(ontimeout);
}
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
opts.callback(true, false, null, { 'message': 'Could not connect to host', 'error': event } );
};
request.send(body);
},
/*
* Transform search param object in query string
*/
_getSearchParams: function(args, params) {
if (this._isUndefined(args) || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args.hasOwnProperty(key)) {
params += (params.length === 0) ? '?' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? JSON.stringify(args[key]) : args[key]);
}
}
return params;
},
_isUndefined: function(obj) {
return obj === void 0;
},
_support: {
hasXMLHttpRequest: 'XMLHttpRequest' in window,
hasXDomainRequest: 'XDomainRequest' in window,
cors: 'withCredentials' in new XMLHttpRequest(),
timeout: 'timeout' in new XMLHttpRequest()
}
};
/*
* Contains all the functions related to one index
* You should use AlgoliaSearch.initIndex(indexName) to retrieve this object
*/
AlgoliaSearch.prototype.Index.prototype = {
/*
* Clear all queries in cache
*/
clearCache: function() {
this.cache = {};
},
/*
* Add an object in this index
*
* @param content contains the javascript object to add inside the index
* @param callback (optional) the result callback with two arguments:
* success: boolean set to true if the request was successfull
* content: the server answer that contains 3 elements: createAt, taskId and objectID