@@ -6,7 +6,7 @@ require('isomorphic-fetch');
6
6
/**
7
7
* Fetch search results of search suggestions from the Addsearch API
8
8
*/
9
- var executeApiFetch = function ( sitekey , type , settings , cb ) {
9
+ var executeApiFetch = function ( sitekey , type , settings , cb , fuzzyRetry ) {
10
10
11
11
const RESPONSE_BAD_REQUEST = 400 ;
12
12
const RESPONSE_SERVER_ERROR = 500 ;
@@ -46,10 +46,23 @@ var executeApiFetch = function(sitekey, type, settings, cb) {
46
46
// Escape
47
47
kw = encodeURIComponent ( kw ) ;
48
48
49
+ // Fuzzy
50
+ var fuzzy = settings . fuzzy ;
51
+ if ( fuzzy === 'retry' ) {
52
+ // First call, non fuzzy
53
+ if ( fuzzyRetry !== true ) {
54
+ fuzzy = false ;
55
+ }
56
+ // Second call, fuzzy
57
+ else {
58
+ fuzzy = true ;
59
+ }
60
+ }
61
+
49
62
// Construct query string from settings
50
63
if ( type === 'search' ) {
51
64
qs = settingToQueryParam ( settings . lang , 'lang' ) +
52
- settingToQueryParam ( settings . fuzzy , 'fuzzy' ) +
65
+ settingToQueryParam ( fuzzy , 'fuzzy' ) +
53
66
settingToQueryParam ( settings . collectAnalytics , 'collectAnalytics' ) +
54
67
settingToQueryParam ( settings . categories , 'categories' ) +
55
68
settingToQueryParam ( settings . priceFromCents , 'priceFromCents' ) +
@@ -118,7 +131,27 @@ var executeApiFetch = function(sitekey, type, settings, cb) {
118
131
. then ( function ( response ) {
119
132
return response . json ( ) ;
120
133
} ) . then ( function ( json ) {
121
- cb ( json ) ;
134
+
135
+ // Search again with fuzzy=true if no hits
136
+ if ( type === 'search' && settings . fuzzy === 'retry' && json . total_hits === 0 && fuzzyRetry !== true ) {
137
+ executeApiFetch ( sitekey , type , settings , cb , true ) ;
138
+ }
139
+
140
+ // Fuzzy not "retry" OR fuzzyRetry already returning
141
+ else {
142
+
143
+ // Cap fuzzy results to one page as quality decreases quickly
144
+ if ( fuzzyRetry === true ) {
145
+ var pageSize = settings . paging . pageSize ;
146
+ if ( json . total_hits >= pageSize ) {
147
+ json . total_hits = pageSize ;
148
+ }
149
+ }
150
+
151
+ // Callback
152
+ cb ( json ) ;
153
+ }
154
+
122
155
} ) . catch ( function ( ex ) {
123
156
console . log ( ex ) ;
124
157
cb ( { error : { response : RESPONSE_SERVER_ERROR , message : 'invalid server response' } } ) ;
0 commit comments