@@ -6,7 +6,7 @@ require('isomorphic-fetch');
66/**
77 * Fetch search results of search suggestions from the Addsearch API
88 */
9- var executeApiFetch = function ( sitekey , type , settings , cb ) {
9+ var executeApiFetch = function ( sitekey , type , settings , cb , fuzzyRetry ) {
1010
1111 const RESPONSE_BAD_REQUEST = 400 ;
1212 const RESPONSE_SERVER_ERROR = 500 ;
@@ -46,10 +46,23 @@ var executeApiFetch = function(sitekey, type, settings, cb) {
4646 // Escape
4747 kw = encodeURIComponent ( kw ) ;
4848
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+
4962 // Construct query string from settings
5063 if ( type === 'search' ) {
5164 qs = settingToQueryParam ( settings . lang , 'lang' ) +
52- settingToQueryParam ( settings . fuzzy , 'fuzzy' ) +
65+ settingToQueryParam ( fuzzy , 'fuzzy' ) +
5366 settingToQueryParam ( settings . collectAnalytics , 'collectAnalytics' ) +
5467 settingToQueryParam ( settings . categories , 'categories' ) +
5568 settingToQueryParam ( settings . priceFromCents , 'priceFromCents' ) +
@@ -118,7 +131,27 @@ var executeApiFetch = function(sitekey, type, settings, cb) {
118131 . then ( function ( response ) {
119132 return response . json ( ) ;
120133 } ) . 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+
122155 } ) . catch ( function ( ex ) {
123156 console . log ( ex ) ;
124157 cb ( { error : { response : RESPONSE_SERVER_ERROR , message : 'invalid server response' } } ) ;
0 commit comments