Skip to content

Commit 230ff1b

Browse files
committed
Add throttle to API queries
1 parent 7843c40 commit 230ff1b

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/index.js

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ var executeApiFetch = require('./apifetch');
44
var sendStats = require('./stats');
55
var Settings = require('./settings');
66
var util = require('./util');
7+
var throttle = require('./throttle');
8+
9+
var API_THROTTLE = 200;
710

811
var client = function(sitekey) {
912
this.sitekey = sitekey;
@@ -44,7 +47,11 @@ var client = function(sitekey) {
4447

4548
this.settings.setCallback(callback);
4649
this.settings.setKeyword(keyword);
47-
executeApiFetch(this.sitekey, 'search', this.settings.getSettings(), callback);
50+
51+
if (!this.throttledSearchFetch) {
52+
this.throttledSearchFetch = throttle(API_THROTTLE, executeApiFetch);
53+
}
54+
this.throttledSearchFetch(this.sitekey, 'search', this.settings.getSettings(), callback);
4855
}
4956

5057

@@ -58,7 +65,11 @@ var client = function(sitekey) {
5865
throw "Illegal suggestions parameters. Should be (prefix, callbackFunction)";
5966
}
6067
this.settings.setSuggestionsPrefix(prefix);
61-
executeApiFetch(this.sitekey, 'suggest', this.settings.getSettings(), callback);
68+
69+
if (!this.throttledSuggestionsFetch) {
70+
this.throttledSuggestionsFetch = throttle(API_THROTTLE, executeApiFetch);
71+
}
72+
this.throttledSuggestionsFetch(this.sitekey, 'suggest', this.settings.getSettings(), callback);
6273
}
6374

6475

@@ -72,7 +83,11 @@ var client = function(sitekey) {
7283
throw "Illegal autocomplete parameters. Should be (field, prefix, callbackFunction)";
7384
}
7485
this.settings.setAutocompleteParams(field, prefix);
75-
executeApiFetch(this.sitekey, 'autocomplete', this.settings.getSettings(), callback);
86+
87+
if (!this.throttledAutocompleteFetch) {
88+
this.throttledAutocompleteFetch = throttle(API_THROTTLE, executeApiFetch);
89+
}
90+
this.throttledAutocompleteFetch(this.sitekey, 'autocomplete', this.settings.getSettings(), callback);
7691
}
7792

7893

@@ -101,6 +116,7 @@ var client = function(sitekey) {
101116
this.setShuffleAndLimitTo = function(shuffleAndLimitTo) { this.settings.setShuffleAndLimitTo(shuffleAndLimitTo); }
102117
this.setFuzzyMatch = function(fuzzy) { this.settings.setFuzzyMatch(fuzzy); }
103118
this.setCollectAnalytics = function(collectAnalytics) { this.settings.setCollectAnalytics(collectAnalytics); }
119+
this.setThrottleDelay = function(delay) { API_THROTTLE = delay; }
104120
this.setStatsSessionId = function(id) { this.sessionId = id; }
105121
this.getStatsSessionId = function() { return this.sessionId; }
106122

0 commit comments

Comments
 (0)