Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ffd06fb

Browse files
committedNov 6, 2024
add prettier for consistent formatting
1 parent faa4436 commit ffd06fb

20 files changed

+833
-562
lines changed
 

‎.prettierignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules
2+
dist

‎.prettierrc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"printWidth": 100,
3+
"trailingComma": "none",
4+
"tabWidth": 2,
5+
"semi": true,
6+
"singleQuote": true,
7+
"bracketSpacing": true,
8+
"bracketSameLine": false,
9+
"arrowParens": "always",
10+
"endOfLine": "auto",
11+
"jsxSingleQuote": false,
12+
"proseWrap": "always",
13+
"quoteProps": "consistent",
14+
"useTabs": false,
15+
"htmlWhitespaceSensitivity": "css"
16+
}

‎README.md

Lines changed: 232 additions & 140 deletions
Large diffs are not rendered by default.

‎index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
"use strict"
1+
'use strict';
22

3-
module.exports = require("./src/index.js")
3+
module.exports = require('./src/index.js');

‎package-lock.json

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,6 @@
22
"name": "addsearch-js-client",
33
"version": "0.8.14",
44
"description": "AddSearch API JavaScript client",
5-
"main": "index.js",
6-
"jsdelivr": "./dist/addsearch-js-client.min.js",
7-
"scripts": {
8-
"test": "./node_modules/mocha/bin/mocha.js --recursive --require @babel/register",
9-
"build": "npm run test && ./node_modules/webpack-cli/bin/cli.js",
10-
"watch": "./node_modules/webpack-cli/bin/cli.js --watch"
11-
},
125
"repository": {
136
"type": "git",
147
"url": "git://github.com/AddSearch/js-client-library.git"
@@ -34,7 +27,19 @@
3427
"url": "https://www.addsearch.com"
3528
}
3629
],
37-
"license": "MIT",
30+
"main": "index.js",
31+
"jsdelivr": "./dist/addsearch-js-client.min.js",
32+
"types": "index.d.ts",
33+
"files": [
34+
"dist",
35+
"index.d.ts"
36+
],
37+
"scripts": {
38+
"build": "npm run test && ./node_modules/webpack-cli/bin/cli.js",
39+
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
40+
"test": "./node_modules/mocha/bin/mocha.js --recursive --require @babel/register",
41+
"watch": "./node_modules/webpack-cli/bin/cli.js --watch"
42+
},
3843
"dependencies": {
3944
"axios": "^1.7.2",
4045
"es6-promise": "^4.2.8",
@@ -54,6 +59,7 @@
5459
"esm": "^3.2.25",
5560
"fetch-mock": "^9.11.0",
5661
"mocha": "^10.0.0",
62+
"prettier": "^3.3.3",
5763
"terser-webpack-plugin": "^5.3.1",
5864
"uglify-js": "^3.12.0",
5965
"webpack": "^5.76.1",

‎src/api.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,19 @@ const statsInstance = axios.create();
66

77
const setRequestInterceptor = (callback, requestType) => {
88
const axiosInstance = requestType === 'searchApi' ? apiInstance : statsInstance;
9-
axiosInstance.interceptors.request.use( (config) => {
10-
const updatedConfig = callback({
11-
url: config.url,
12-
headers: config.headers
13-
});
14-
config = {...config, ...updatedConfig};
15-
return config;
16-
}, function (error) {
17-
return Promise.reject(error);
18-
});
9+
axiosInstance.interceptors.request.use(
10+
(config) => {
11+
const updatedConfig = callback({
12+
url: config.url,
13+
headers: config.headers
14+
});
15+
config = { ...config, ...updatedConfig };
16+
return config;
17+
},
18+
function (error) {
19+
return Promise.reject(error);
20+
}
21+
);
1922
};
2023

2124
module.exports = {

‎src/apifetch.js

Lines changed: 56 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,29 @@ const apiInstance = require('./api').apiInstance;
66
/**
77
* Fetch search results of search suggestions from the Addsearch API
88
*/
9-
var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRetry, customFilterObject, recommendOptions) {
10-
9+
var executeApiFetch = function (
10+
apiHostname,
11+
sitekey,
12+
type,
13+
settings,
14+
cb,
15+
fuzzyRetry,
16+
customFilterObject,
17+
recommendOptions
18+
) {
1119
const RESPONSE_BAD_REQUEST = 400;
1220
const RESPONSE_SERVER_ERROR = 500;
1321

14-
var settingToQueryParam = function(setting, key) {
22+
var settingToQueryParam = function (setting, key) {
1523
if (setting || setting === false) {
1624
return '&' + key + '=' + setting;
1725
}
1826
return '';
1927
};
2028

21-
2229
// Validate query type
2330
if (type !== 'search' && type !== 'suggest' && type !== 'autocomplete' && type !== 'recommend') {
24-
cb({error: {response: RESPONSE_BAD_REQUEST, message: 'invalid query type'}});
31+
cb({ error: { response: RESPONSE_BAD_REQUEST, message: 'invalid query type' } });
2532
return;
2633
}
2734

@@ -42,9 +49,9 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
4249
kw = settings.keyword;
4350

4451
// Boolean operators (AND, OR, NOT) uppercase
45-
kw = settings.enableLogicalOperators ?
46-
kw.replace(/ and /g, ' AND ').replace(/ or /g, ' OR ').replace(/ not /g, ' NOT ') :
47-
kw.replace(/ AND /g, ' and ').replace(/ OR /g, ' or ').replace(/ NOT /g, ' not ');
52+
kw = settings.enableLogicalOperators
53+
? kw.replace(/ and /g, ' AND ').replace(/ or /g, ' OR ').replace(/ not /g, ' NOT ')
54+
: kw.replace(/ AND /g, ' and ').replace(/ OR /g, ' or ').replace(/ NOT /g, ' not ');
4855

4956
// Escape
5057
kw = encodeURIComponent(kw);
@@ -64,7 +71,8 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
6471

6572
// Construct query string from settings
6673
if (type === 'search') {
67-
qs = settingToQueryParam(settings.lang, 'lang') +
74+
qs =
75+
settingToQueryParam(settings.lang, 'lang') +
6876
settingToQueryParam(fuzzy, 'fuzzy') +
6977
settingToQueryParam(settings.collectAnalytics, 'collectAnalytics') +
7078
settingToQueryParam(settings.postfixWildcard, 'postfixWildcard') +
@@ -86,12 +94,16 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
8694

8795
// Add sortBy and sortOrder
8896
if (Array.isArray(settings.paging.sortBy)) {
89-
settings.paging.sortBy.forEach(function(value, index) {
90-
qs = qs + settingToQueryParam(value, 'sort') +
97+
settings.paging.sortBy.forEach(function (value, index) {
98+
qs =
99+
qs +
100+
settingToQueryParam(value, 'sort') +
91101
settingToQueryParam(settings.paging.sortOrder[index], 'order');
92102
});
93103
} else {
94-
qs = qs + settingToQueryParam(settings.paging.sortBy, 'sort') +
104+
qs =
105+
qs +
106+
settingToQueryParam(settings.paging.sortBy, 'sort') +
95107
settingToQueryParam(settings.paging.sortOrder, 'order');
96108
}
97109

@@ -104,34 +116,34 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
104116

105117
// Add facet fields
106118
if (settings.facetFields) {
107-
for (let i = 0; i<settings.facetFields.length; i++) {
119+
for (let i = 0; i < settings.facetFields.length; i++) {
108120
qs = qs + '&facet=' + settings.facetFields[i];
109121
}
110122
}
111123

112-
113124
// Range facets
114125
if (settings.rangeFacets) {
115126
qs = qs + '&rangeFacets=' + encodeURIComponent(JSON.stringify(settings.rangeFacets));
116127
}
117128

118129
// Hierarchical facets
119130
if (settings.hierarchicalFacetSetting) {
120-
qs = qs + '&hierarchicalFacets=' + encodeURIComponent(JSON.stringify(settings.hierarchicalFacetSetting));
131+
qs =
132+
qs +
133+
'&hierarchicalFacets=' +
134+
encodeURIComponent(JSON.stringify(settings.hierarchicalFacetSetting));
121135
}
122136

123-
124137
// Stats fields
125138
if (settings.statsFields) {
126-
for (var i = 0; i<settings.statsFields.length; i++) {
139+
for (var i = 0; i < settings.statsFields.length; i++) {
127140
qs = qs + '&fieldStat=' + settings.statsFields[i];
128141
}
129142
}
130143

131-
132144
// Personalization events
133145
if (settings.personalizationEvents && Array.isArray(settings.personalizationEvents)) {
134-
for (let i = 0; i<settings.personalizationEvents.length; i++) {
146+
for (let i = 0; i < settings.personalizationEvents.length; i++) {
135147
var obj = settings.personalizationEvents[i];
136148
var key = Object.keys(obj);
137149
qs = qs + '&personalizationEvent=' + encodeURIComponent(key + '=' + obj[key]);
@@ -144,15 +156,15 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
144156
} else if (settings.filterObject) {
145157
qs = qs + '&filter=' + encodeURIComponent(JSON.stringify(settings.filterObject));
146158
}
147-
148159
}
149160
api = 'https://' + apiHostname + '/v1/' + apiPath + '/' + sitekey + '?term=' + kw + qs;
150161
}
151162

152163
// Suggest
153164
else if (type === 'suggest') {
154165
apiPath = type;
155-
qs = settingToQueryParam(settings.suggestionsSize, 'size') +
166+
qs =
167+
settingToQueryParam(settings.suggestionsSize, 'size') +
156168
settingToQueryParam(settings.lang, 'language');
157169
kw = settings.suggestionsPrefix;
158170
api = 'https://' + apiHostname + '/v1/' + apiPath + '/' + sitekey + '?term=' + kw + qs;
@@ -161,34 +173,44 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
161173
// Autocomplete
162174
else if (type === 'autocomplete') {
163175
apiPath = 'autocomplete/document-field';
164-
qs = settingToQueryParam(settings.autocomplete.field, 'source') +
165-
settingToQueryParam(settings.autocomplete.size, 'size');
176+
qs =
177+
settingToQueryParam(settings.autocomplete.field, 'source') +
178+
settingToQueryParam(settings.autocomplete.size, 'size');
166179
kw = settings.autocomplete.prefix;
167180
api = 'https://' + apiHostname + '/v1/' + apiPath + '/' + sitekey + '?term=' + kw + qs;
168-
}
169-
170-
else if (type === 'recommend') {
181+
} else if (type === 'recommend') {
171182
if (recommendOptions.type === 'RELATED_ITEMS') {
172183
qs = settingToQueryParam(recommendOptions.itemId, 'itemId');
173-
apiPath = 'recommendations/index/' + sitekey + '/block/' + recommendOptions.blockId + '?' + qs;
184+
apiPath =
185+
'recommendations/index/' + sitekey + '/block/' + recommendOptions.blockId + '?' + qs;
174186
} else if (recommendOptions.type === 'FREQUENTLY_BOUGHT_TOGETHER') {
175187
qs = settingToQueryParam(recommendOptions.itemId, 'itemId');
176-
apiPath = 'recommendations/' + sitekey + '?configurationKey=' + recommendOptions.configurationKey + qs;
188+
apiPath =
189+
'recommendations/' +
190+
sitekey +
191+
'?configurationKey=' +
192+
recommendOptions.configurationKey +
193+
qs;
177194
}
178195
api = 'https://' + apiHostname + '/v1/' + apiPath;
179196
}
180197

181-
apiInstance.get(api)
182-
.then(function(response) {
198+
apiInstance
199+
.get(api)
200+
.then(function (response) {
183201
var json = response.data;
184202
// Search again with fuzzy=true if no hits
185-
if (type === 'search' && settings.fuzzy === 'retry' && json.total_hits === 0 && fuzzyRetry !== true) {
203+
if (
204+
type === 'search' &&
205+
settings.fuzzy === 'retry' &&
206+
json.total_hits === 0 &&
207+
fuzzyRetry !== true
208+
) {
186209
executeApiFetch(apiHostname, sitekey, type, settings, cb, true);
187210
}
188211

189212
// Fuzzy not "retry" OR fuzzyRetry already returning
190213
else {
191-
192214
// Cap fuzzy results to one page as quality decreases quickly
193215
if (fuzzyRetry === true) {
194216
var pageSize = settings.paging.pageSize;
@@ -201,9 +223,9 @@ var executeApiFetch = function(apiHostname, sitekey, type, settings, cb, fuzzyRe
201223
cb(json);
202224
}
203225
})
204-
.catch(function(ex) {
226+
.catch(function (ex) {
205227
console.log(ex);
206-
cb({error: {response: RESPONSE_SERVER_ERROR, message: 'invalid server response'}});
228+
cb({ error: { response: RESPONSE_SERVER_ERROR, message: 'invalid server response' } });
207229
});
208230
};
209231
module.exports = executeApiFetch;

‎src/cookie.js

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
const setCookie = function(cookieName, cookieValue, expireDays) {
1+
const setCookie = function (cookieName, cookieValue, expireDays) {
22
if (typeof document === 'undefined') {
33
return;
44
}
55
const date = new Date();
6-
date.setTime(date.getTime() + (expireDays * 24 * 60 * 60 * 1000));
7-
let expires = "expires="+ date.toUTCString();
8-
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
9-
}
6+
date.setTime(date.getTime() + expireDays * 24 * 60 * 60 * 1000);
7+
let expires = 'expires=' + date.toUTCString();
8+
document.cookie = cookieName + '=' + cookieValue + ';' + expires + ';path=/';
9+
};
1010

11-
const getCookie = function(cookieName) {
11+
const getCookie = function (cookieName) {
1212
if (typeof document === 'undefined') {
1313
return;
1414
}
15-
let name = cookieName + "=";
15+
let name = cookieName + '=';
1616
let decodedCookie = decodeURIComponent(document.cookie);
1717
let cookieArray = decodedCookie.split(';');
18-
for(let i = 0; i < cookieArray.length; i++) {
18+
for (let i = 0; i < cookieArray.length; i++) {
1919
let cookie = cookieArray[i];
2020
while (cookie.charAt(0) === ' ') {
2121
cookie = cookie.substring(1);
@@ -25,17 +25,17 @@ const getCookie = function(cookieName) {
2525
}
2626
}
2727
return undefined;
28-
}
28+
};
2929

30-
const deleteCookie = function(name) {
30+
const deleteCookie = function (name) {
3131
if (typeof document === 'undefined') {
3232
return;
3333
}
34-
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 2000 00:00:01 GMT;';
35-
}
34+
document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 2000 00:00:01 GMT;';
35+
};
3636

3737
module.exports = {
3838
setCookie,
3939
getCookie,
4040
deleteCookie
41-
}
41+
};

‎src/index.js

Lines changed: 236 additions & 110 deletions
Large diffs are not rendered by default.

‎src/indexingapi.js

Lines changed: 59 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -4,34 +4,32 @@ const util = require('./util');
44
const Promise = require('es6-promise').Promise;
55
const axios = require('axios').default;
66

7-
const getHeaders = function(sitekey, privatekey) {
7+
const getHeaders = function (sitekey, privatekey) {
88
return {
99
'Authorization': 'Basic ' + util.base64(sitekey + ':' + privatekey),
1010
'Content-Type': 'application/json'
1111
};
12-
}
13-
12+
};
1413

1514
/**
1615
* Fetch document
1716
*/
18-
var getDocument = function(apiHostname, sitekey, privatekey, id) {
17+
var getDocument = function (apiHostname, sitekey, privatekey, id) {
1918
const promise = new Promise((resolve, reject) => {
20-
21-
axios.get('https://' + apiHostname + '/v2/indices/' + sitekey + '/documents/' + id,
22-
{
19+
axios
20+
.get('https://' + apiHostname + '/v2/indices/' + sitekey + '/documents/' + id, {
2321
headers: getHeaders(sitekey, privatekey)
2422
})
2523
.then((response) => {
2624
if (response.status == 200) {
2725
resolve(response.data);
26+
} else {
27+
reject({ status: response.status, text: response.statusText });
2828
}
29-
else {
30-
reject({status: response.status, text: response.statusText});
31-
}
32-
}).catch((ex) => {
33-
reject({status: 400, text: ex});
34-
});
29+
})
30+
.catch((ex) => {
31+
reject({ status: 400, text: ex });
32+
});
3533
});
3634

3735
return promise;
@@ -40,120 +38,112 @@ var getDocument = function(apiHostname, sitekey, privatekey, id) {
4038
/**
4139
* Add document
4240
*/
43-
var saveDocument = function(apiHostname, sitekey, privatekey, document) {
44-
41+
var saveDocument = function (apiHostname, sitekey, privatekey, document) {
4542
// If the doc has id or url field, PUT instead of POST
4643

4744
const isPut = document.id || document.url;
4845

4946
const promise = new Promise((resolve, reject) => {
50-
axios(
51-
{
52-
url: 'https://' + apiHostname + '/v2/indices/' + sitekey + '/documents/',
53-
method: isPut ? 'put' : 'post',
54-
headers: getHeaders(sitekey, privatekey),
55-
data: document
56-
})
47+
axios({
48+
url: 'https://' + apiHostname + '/v2/indices/' + sitekey + '/documents/',
49+
method: isPut ? 'put' : 'post',
50+
headers: getHeaders(sitekey, privatekey),
51+
data: document
52+
})
5753
.then((response) => {
5854
if (response.status == 202) {
59-
resolve({status: response.status, text: response.statusText});
55+
resolve({ status: response.status, text: response.statusText });
56+
} else {
57+
reject({ status: response.status, text: response.statusText });
6058
}
61-
else {
62-
reject({status: response.status, text: response.statusText});
63-
}
64-
}).catch((ex) => {
65-
reject({status: 400, text: ex});
59+
})
60+
.catch((ex) => {
61+
reject({ status: 400, text: ex });
6662
});
6763
});
6864

6965
return promise;
7066
};
7167

72-
7368
/**
7469
* Batch add documents
7570
*/
76-
var saveDocumentsBatch = function(apiHostname, sitekey, privatekey, documents) {
77-
71+
var saveDocumentsBatch = function (apiHostname, sitekey, privatekey, documents) {
7872
const promise = new Promise((resolve, reject) => {
79-
axios(
80-
{
81-
method: 'put',
82-
url: 'https://' + apiHostname + '/v2/indices/' + sitekey + '/documents:batch',
83-
headers: getHeaders(sitekey, privatekey),
84-
data: documents
85-
})
73+
axios({
74+
method: 'put',
75+
url: 'https://' + apiHostname + '/v2/indices/' + sitekey + '/documents:batch',
76+
headers: getHeaders(sitekey, privatekey),
77+
data: documents
78+
})
8679
.then((response) => {
8780
if (response.status == 202) {
88-
resolve({status: response.status, text: response.statusText});
89-
}
90-
else {
91-
reject({status: response.status, text: response.statusText});
81+
resolve({ status: response.status, text: response.statusText });
82+
} else {
83+
reject({ status: response.status, text: response.statusText });
9284
}
93-
}).catch((ex) => {
94-
reject({status: 400, text: ex});
95-
});
85+
})
86+
.catch((ex) => {
87+
reject({ status: 400, text: ex });
88+
});
9689
});
9790

9891
return promise;
9992
};
10093

101-
10294
/**
10395
* Delete documents
10496
*/
105-
var deleteDocument = function(apiHostname, sitekey, privatekey, id) {
97+
var deleteDocument = function (apiHostname, sitekey, privatekey, id) {
10698
const promise = new Promise((resolve, reject) => {
107-
axios.delete('https://' + apiHostname + '/v2/indices/' + sitekey + '/documents/' + id,
108-
{
99+
axios
100+
.delete('https://' + apiHostname + '/v2/indices/' + sitekey + '/documents/' + id, {
109101
headers: getHeaders(sitekey, privatekey)
110102
})
111103
.then((response) => {
112104
if (response.status == 202) {
113-
resolve({status: response.status, text: response.statusText});
114-
}
115-
else {
116-
reject({status: response.status, text: response.statusText});
105+
resolve({ status: response.status, text: response.statusText });
106+
} else {
107+
reject({ status: response.status, text: response.statusText });
117108
}
118-
}).catch((ex) => {
119-
reject({status: 400, text: ex});
120-
});
109+
})
110+
.catch((ex) => {
111+
reject({ status: 400, text: ex });
112+
});
121113
});
122114

123115
return promise;
124116
};
125117

126-
127118
/**
128119
* Batch delete documents
129120
*/
130-
var deleteDocumentsBatch = function(apiHostname, sitekey, privatekey, batch) {
121+
var deleteDocumentsBatch = function (apiHostname, sitekey, privatekey, batch) {
131122
const promise = new Promise((resolve, reject) => {
132-
axios.delete('https://' + apiHostname + '/v2/indices/' + sitekey + '/documents:batch',
133-
{
123+
axios
124+
.delete('https://' + apiHostname + '/v2/indices/' + sitekey + '/documents:batch', {
134125
headers: getHeaders(sitekey, privatekey),
135126
data: batch
136127
})
137128
.then((response) => {
138129
if (response.status == 202) {
139-
resolve({status: response.status, text: response.statusText});
130+
resolve({ status: response.status, text: response.statusText });
131+
} else {
132+
reject({ status: response.status, text: response.statusText });
140133
}
141-
else {
142-
reject({status: response.status, text: response.statusText});
143-
}
144-
}).catch((ex) => {
145-
reject({status: 400, text: ex});
146-
});
134+
})
135+
.catch((ex) => {
136+
reject({ status: 400, text: ex });
137+
});
147138
});
148139

149140
return promise;
150141
};
151142

152-
153143
module.exports = {
154144
getDocument,
155145
saveDocument,
156146
saveDocumentsBatch,
157147
deleteDocument,
158148
deleteDocumentsBatch
159-
};
149+
};

‎src/settings.js

Lines changed: 85 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use strict';
22

33
var util = require('./util');
4-
var settings = function() {
4+
var settings = function () {
55
this.settings = {
66
keyword: '*',
77
callback: null,
@@ -23,107 +23,107 @@ var settings = function() {
2323
searchOperator: null,
2424
enableLogicalOperators: false,
2525
cacheResponseTime: null,
26-
statsRequestIntercepted: false,
26+
statsRequestIntercepted: false
2727
};
2828

29-
this.getSettings = function() {
29+
this.getSettings = function () {
3030
return this.settings;
31-
}
31+
};
3232

33-
this.setKeyword = function(keyword) {
33+
this.setKeyword = function (keyword) {
3434
this.settings.keyword = keyword || '*';
35-
}
35+
};
3636

37-
this.setCallback = function(cb) {
37+
this.setCallback = function (cb) {
3838
this.settings.callback = cb;
39-
}
39+
};
4040

41-
this.setThrottleTime = function(delay) {
41+
this.setThrottleTime = function (delay) {
4242
this.settings.throttleTimeMs = delay;
43-
}
43+
};
4444

45-
this.setSuggestionsPrefix = function(prefix) {
45+
this.setSuggestionsPrefix = function (prefix) {
4646
this.settings.suggestionsPrefix = prefix;
47-
}
47+
};
4848

49-
this.setSuggestionsSize = function(size) {
49+
this.setSuggestionsSize = function (size) {
5050
this.settings.suggestionsSize = size;
51-
}
51+
};
5252

53-
this.setAutocompleteSize = function(size) {
53+
this.setAutocompleteSize = function (size) {
5454
this.settings.autocomplete.size = size;
55-
}
55+
};
5656

57-
this.setAutocompleteParams = function(field, prefix) {
57+
this.setAutocompleteParams = function (field, prefix) {
5858
this.settings.autocomplete.field = field;
5959
this.settings.autocomplete.prefix = prefix;
60-
}
60+
};
6161

62-
this.setLanguage = function(language) {
62+
this.setLanguage = function (language) {
6363
var languageIntlLocale;
6464
if (Intl && Intl.Locale) {
6565
try {
6666
languageIntlLocale = new Intl.Locale(language).language;
6767
} catch (e) {
68-
throw "use accepted language code provided by ECMAScript Internationalization API (e.g. \"en\", \"en-GB\")";
68+
throw 'use accepted language code provided by ECMAScript Internationalization API (e.g. "en", "en-GB")';
6969
}
7070
} else {
7171
languageIntlLocale = language;
7272
}
7373
if (languageIntlLocale && languageIntlLocale.length !== 2) {
74-
throw "use 2-char/4-char language code (e.g. \"en\", \"en-GB\")";
74+
throw 'use 2-char/4-char language code (e.g. "en", "en-GB")';
7575
}
7676
this.settings.lang = languageIntlLocale;
77-
}
77+
};
7878

79-
this.setFuzzyMatch = function(fuzzy) {
79+
this.setFuzzyMatch = function (fuzzy) {
8080
if (fuzzy !== true && fuzzy !== false && fuzzy !== 'auto' && fuzzy !== 'retry') {
8181
throw "fuzzy matching can be true, false, 'auto', or 'retry'";
8282
}
8383
this.settings.fuzzy = fuzzy;
84-
}
84+
};
8585

86-
this.enableLogicalOperators = function(enableLogicalOperators) {
86+
this.enableLogicalOperators = function (enableLogicalOperators) {
8787
this.settings.enableLogicalOperators = enableLogicalOperators;
88-
}
88+
};
8989

90-
this.setCacheResponseTime = function(cacheResponseTime) {
90+
this.setCacheResponseTime = function (cacheResponseTime) {
9191
this.settings.cacheResponseTime = cacheResponseTime;
92-
}
92+
};
9393

94-
this.setPostfixWildcard = function(wildcard) {
94+
this.setPostfixWildcard = function (wildcard) {
9595
this.settings.postfixWildcard = wildcard;
96-
}
96+
};
9797

98-
this.setCollectAnalytics = function(collectAnalytics) {
98+
this.setCollectAnalytics = function (collectAnalytics) {
9999
this.settings.collectAnalytics = collectAnalytics;
100-
}
100+
};
101101

102-
this.setAnalyticsTag = function(tagName) {
102+
this.setAnalyticsTag = function (tagName) {
103103
this.settings.analyticsTag = tagName;
104-
}
104+
};
105105

106-
this.setCategoryFilters = function(categories) {
106+
this.setCategoryFilters = function (categories) {
107107
this.settings.categories = categories;
108-
}
108+
};
109109

110-
this.setFilterObject = function(filter) {
111-
this.settings.filterObject= filter;
112-
}
110+
this.setFilterObject = function (filter) {
111+
this.settings.filterObject = filter;
112+
};
113113

114-
this.setPriceRangeFilter = function(minCents, maxCents) {
114+
this.setPriceRangeFilter = function (minCents, maxCents) {
115115
this.settings.priceFromCents = minCents;
116116
this.settings.priceToCents = maxCents;
117-
}
117+
};
118118

119-
this.addCustomFieldFilter = function(fieldName, value) {
119+
this.addCustomFieldFilter = function (fieldName, value) {
120120
var filter = encodeURIComponent(fieldName + '=' + value);
121121
if (this.settings.customFieldFilters.indexOf(filter) === -1) {
122122
this.settings.customFieldFilters.push(filter);
123123
}
124-
}
124+
};
125125

126-
this.removeCustomFieldFilter = function(fieldName, value) {
126+
this.removeCustomFieldFilter = function (fieldName, value) {
127127
var removeAll = false;
128128
var filter = encodeURIComponent(fieldName + '=' + value);
129129

@@ -133,110 +133,109 @@ var settings = function() {
133133
filter = encodeURIComponent(fieldName + '=');
134134
}
135135

136-
for (var i=this.settings.customFieldFilters.length; i>0; i--) {
137-
var v = this.settings.customFieldFilters[i-1];
136+
for (var i = this.settings.customFieldFilters.length; i > 0; i--) {
137+
var v = this.settings.customFieldFilters[i - 1];
138138

139139
if (removeAll && v.indexOf(filter) === 0) {
140-
this.settings.customFieldFilters.splice(i-1, 1);
141-
}
142-
else if (v === filter) {
143-
this.settings.customFieldFilters.splice(i-1, 1);
140+
this.settings.customFieldFilters.splice(i - 1, 1);
141+
} else if (v === filter) {
142+
this.settings.customFieldFilters.splice(i - 1, 1);
144143
}
145144
}
146-
}
145+
};
147146

148-
this.setDateFilter = function(dateFrom, dateTo) {
147+
this.setDateFilter = function (dateFrom, dateTo) {
149148
this.settings.dateFrom = dateFrom;
150149
this.settings.dateTo = dateTo;
151-
}
150+
};
152151

153-
this.setKeyword = function(keyword) {
152+
this.setKeyword = function (keyword) {
154153
this.settings.keyword = keyword || '*';
155-
}
154+
};
156155

157-
this.setJWT = function(jwt) {
156+
this.setJWT = function (jwt) {
158157
this.settings.jwt = jwt;
159-
}
158+
};
160159

161-
this.setUserToken = function(token) {
160+
this.setUserToken = function (token) {
162161
this.settings.userToken = token;
163-
}
162+
};
164163

165-
this.setPersonalizationEvents = function(events) {
164+
this.setPersonalizationEvents = function (events) {
166165
this.settings.personalizationEvents = events;
167-
}
166+
};
168167

169-
this.setResultType = function(type) {
168+
this.setResultType = function (type) {
170169
this.settings.resultType = type;
171-
}
170+
};
172171

173-
this.addFacetField = function(field) {
172+
this.addFacetField = function (field) {
174173
if (this.settings.facetFields.indexOf(field) === -1) {
175174
this.settings.facetFields.push(field);
176175
}
177-
}
176+
};
178177

179-
this.addHierarchicalFacetSetting = function(setting) {
178+
this.addHierarchicalFacetSetting = function (setting) {
180179
this.settings.hierarchicalFacetSetting = setting;
181-
}
180+
};
182181

183-
this.addRangeFacet = function(field, ranges) {
182+
this.addRangeFacet = function (field, ranges) {
184183
if (!this.settings.rangeFacets) {
185184
this.settings.rangeFacets = [];
186185
}
187186
this.settings.rangeFacets.push({
188187
field: field,
189188
ranges: ranges
190189
});
191-
}
190+
};
192191

193-
this.addStatsField = function(field) {
192+
this.addStatsField = function (field) {
194193
if (!this.settings.statsFields) {
195194
this.settings.statsFields = [];
196195
}
197196
if (this.settings.statsFields.indexOf(field) === -1) {
198197
this.settings.statsFields.push(field);
199198
}
200-
}
199+
};
201200

202-
this.setNumberOfFacets = function(numFacets) {
201+
this.setNumberOfFacets = function (numFacets) {
203202
this.settings.numFacets = numFacets;
204-
}
203+
};
205204

206-
this.setPaging = function(page, pageSize, sortBy, sortOrder) {
205+
this.setPaging = function (page, pageSize, sortBy, sortOrder) {
207206
// Validate
208207
util.validateSetPagingParams(page, pageSize, sortBy, sortOrder);
209208

210209
this.settings.paging.page = page;
211210
this.settings.paging.pageSize = pageSize;
212211
this.settings.paging.sortBy = sortBy;
213212
this.settings.paging.sortOrder = sortOrder;
214-
}
213+
};
215214

216-
this.setShuffleAndLimitTo = function(shuffleAndLimitTo) {
215+
this.setShuffleAndLimitTo = function (shuffleAndLimitTo) {
217216
this.settings.shuffleAndLimitTo = shuffleAndLimitTo;
218-
}
217+
};
219218

220-
this.nextPage = function() {
219+
this.nextPage = function () {
221220
this.settings.paging.page = this.settings.paging.page + 1;
222-
}
221+
};
223222

224-
this.previousPage = function() {
223+
this.previousPage = function () {
225224
if (this.settings.paging.page > 0) {
226225
this.settings.paging.page = this.settings.paging.page - 1;
227226
}
228-
}
227+
};
229228

230-
this.setSearchOperator = function(operator) {
229+
this.setSearchOperator = function (operator) {
231230
if (operator !== 'and' && operator !== 'or') {
232-
throw "operator must be 'and' || 'or'"
231+
throw "operator must be 'and' || 'or'";
233232
}
234233
this.settings.searchOperator = operator;
235-
}
234+
};
236235

237-
this.setStatsRequestIntercepted = function(isIntercepted) {
236+
this.setStatsRequestIntercepted = function (isIntercepted) {
238237
this.settings.statsRequestIntercepted = isIntercepted;
239238
};
240-
}
239+
};
241240

242241
module.exports = settings;

‎src/stats.js

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,25 @@
33
require('es6-promise').polyfill();
44
const statsInstance = require('./api').statsInstance;
55

6-
var sendStats = function(apiHostname, sitekey, payload, statsRequestIntercepted) {
7-
6+
var sendStats = function (apiHostname, sitekey, payload, statsRequestIntercepted) {
87
// Beacon in browsers
9-
if (typeof window !== 'undefined' && window.navigator && window.navigator.sendBeacon && !statsRequestIntercepted) {
10-
navigator.sendBeacon('https://' + apiHostname + '/v1/stats/' + sitekey + '/', JSON.stringify(payload));
8+
if (
9+
typeof window !== 'undefined' &&
10+
window.navigator &&
11+
window.navigator.sendBeacon &&
12+
!statsRequestIntercepted
13+
) {
14+
navigator.sendBeacon(
15+
'https://' + apiHostname + '/v1/stats/' + sitekey + '/',
16+
JSON.stringify(payload)
17+
);
1118
}
1219

1320
// POST in node
1421
else {
1522
statsInstance.post('https://' + apiHostname + '/v1/stats/' + sitekey + '/', payload, {
1623
headers: {
17-
'Content-Type': 'text/plain',
24+
'Content-Type': 'text/plain'
1825
}
1926
});
2027
}

‎src/throttle.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
var throttle = function(delay, callback) {
2-
1+
var throttle = function (delay, callback) {
32
// last time callback was executed.
43
var lastExec = 0;
54

@@ -17,7 +16,6 @@ var throttle = function(delay, callback) {
1716
* Wrap the callback inside a throttled function
1817
*/
1918
function wrapper() {
20-
2119
var self = this;
2220
var elapsed = Date.now() - lastExec;
2321
var args = arguments;
@@ -42,6 +40,6 @@ var throttle = function(delay, callback) {
4240

4341
// Return the wrapper function.
4442
return wrapper;
45-
}
43+
};
4644

47-
module.exports = throttle;
45+
module.exports = throttle;

‎src/util.js

Lines changed: 28 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,54 @@
11
const Buffer = require('buffer/').Buffer;
22
const { v4: uuidv4 } = require('uuid');
33

4-
const isFunction = function(fn) {
4+
const isFunction = function (fn) {
55
return fn && {}.toString.call(fn) === '[object Function]';
6-
}
6+
};
77

8-
const base64 = function(s) {
8+
const base64 = function (s) {
99
global.window = {};
1010
if (window && window.btoa) {
1111
return window.btoa(s);
12-
}
13-
else if (Buffer) {
12+
} else if (Buffer) {
1413
return Buffer.from(s).toString('base64');
1514
}
16-
}
15+
};
1716

18-
const validateSetPagingParams = function(page, pageSize, sortBy, sortOrder) {
17+
const validateSetPagingParams = function (page, pageSize, sortBy, sortOrder) {
1918
if (page < 1) {
20-
throw "page must be 1 or bigger";
19+
throw 'page must be 1 or bigger';
2120
}
2221
if (pageSize < 1 || pageSize > 300) {
23-
throw "pageSize must be 1-300";
22+
throw 'pageSize must be 1-300';
2423
}
2524
if (!sortBy || !sortOrder) {
26-
throw "invalid values for sortBy or sortOrder: " + sortBy + ", " + sortOrder;
25+
throw 'invalid values for sortBy or sortOrder: ' + sortBy + ', ' + sortOrder;
2726
}
28-
if (!((typeof sortBy == 'string' && typeof sortOrder == 'string') || (Array.isArray(sortBy) && Array.isArray(sortOrder)))) {
29-
throw "sortBy and sortOrder must have the same type: string or Array";
27+
if (
28+
!(
29+
(typeof sortBy == 'string' && typeof sortOrder == 'string') ||
30+
(Array.isArray(sortBy) && Array.isArray(sortOrder))
31+
)
32+
) {
33+
throw 'sortBy and sortOrder must have the same type: string or Array';
3034
}
3135
if (Array.isArray(sortBy) && sortBy.length !== sortOrder.length) {
32-
throw "sortBy and sortOrder must have the same size";
36+
throw 'sortBy and sortOrder must have the same size';
3337
}
3438
if (typeof sortOrder == 'string' && sortOrder !== 'asc' && sortOrder !== 'desc') {
35-
throw "sortOrder must be asc or desc";
39+
throw 'sortOrder must be asc or desc';
3640
}
37-
if (Array.isArray(sortOrder) &&
38-
sortOrder.filter(function(e) {return e !== 'desc' && e!=='asc'}).length > 0) {
39-
throw "all values of sortOrder array must be asc or desc";
41+
if (
42+
Array.isArray(sortOrder) &&
43+
sortOrder.filter(function (e) {
44+
return e !== 'desc' && e !== 'asc';
45+
}).length > 0
46+
) {
47+
throw 'all values of sortOrder array must be asc or desc';
4048
}
41-
}
49+
};
4250

43-
const generateUUID = function() {
51+
const generateUUID = function () {
4452
return uuidv4().replace(/-/g, '');
4553
};
4654

@@ -49,4 +57,4 @@ module.exports = {
4957
base64,
5058
validateSetPagingParams: validateSetPagingParams,
5159
generateUUID
52-
}
60+
};

‎test/apifetch.js

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,27 @@
11
var assert = require('assert');
22
var apifetch = require('../src/apifetch');
3-
var MockAdapter = require("axios-mock-adapter");
3+
var MockAdapter = require('axios-mock-adapter');
44
var apiInstance = require('../src/api').apiInstance;
55
var mock = new MockAdapter(apiInstance);
66

77
mock.onAny().reply(200, { response: 200 });
88

9-
describe('apifetch', function() {
10-
describe('executeApiFetch', function() {
9+
describe('apifetch', function () {
10+
describe('executeApiFetch', function () {
11+
it('should call callback with response data when query is successful', function () {
12+
const expect = { response: 200 };
1113

12-
it('should call callback with response data when query is successful', function() {
13-
const expect = {response: 200};
14-
15-
apifetch('api.addsearch.com', 'sitekey', 'search', {paging:{}, keyword: 'foo'}, (res) => {
14+
apifetch('api.addsearch.com', 'sitekey', 'search', { paging: {}, keyword: 'foo' }, (res) => {
1615
assert.deepEqual(res, expect);
1716
});
1817
});
1918

20-
it('should return client error when request type is invalid', function() {
19+
it('should return client error when request type is invalid', function () {
2120
const expect = 400;
2221

23-
apifetch('api.addsearch.com', 'sitekey', 'ping', {paging:{}, keyword: 'foo'}, (res) => {
22+
apifetch('api.addsearch.com', 'sitekey', 'ping', { paging: {}, keyword: 'foo' }, (res) => {
2423
assert.equal(res.error.response, expect);
2524
});
2625
});
27-
2826
});
2927
});

‎test/settings.js

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,23 @@
11
var assert = require('assert');
22
var Settings = require('../src/settings');
33

4-
5-
describe('settings', function() {
6-
describe('setLanguage', function() {
7-
8-
it('language setting should be set', function() {
9-
const expect = {lang: 'en'};
4+
describe('settings', function () {
5+
describe('setLanguage', function () {
6+
it('language setting should be set', function () {
7+
const expect = { lang: 'en' };
108
var set = new Settings();
119
set.setLanguage('en');
1210
assert.equal(set.getSettings().lang, expect.lang);
1311
});
1412

15-
16-
1713
var s = new Settings();
18-
it('city london should be added to custom field filters', function() {
14+
it('city london should be added to custom field filters', function () {
1915
s.addCustomFieldFilter('city', 'london');
2016
var expect = '["city%3Dlondon"]';
2117
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
2218
});
2319

24-
it('city berlin and color red should be added to custom field filters', function() {
20+
it('city berlin and color red should be added to custom field filters', function () {
2521
s.addCustomFieldFilter('city', 'berlin');
2622
var expect = '["city%3Dlondon","city%3Dberlin"]';
2723
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
@@ -31,7 +27,7 @@ describe('settings', function() {
3127
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
3228
});
3329

34-
it('color blue should be added and red removed from custom field filters', function() {
30+
it('color blue should be added and red removed from custom field filters', function () {
3531
s.addCustomFieldFilter('color', 'blue');
3632
var expect = '["city%3Dlondon","city%3Dberlin","color%3Dred","color%3Dblue"]';
3733
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
@@ -41,13 +37,13 @@ describe('settings', function() {
4137
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
4238
});
4339

44-
it('all cities should be removed from custom field filters', function() {
40+
it('all cities should be removed from custom field filters', function () {
4541
s.removeCustomFieldFilter('city');
4642
var expect = '["color%3Dblue"]';
4743
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
4844
});
4945

50-
it('all colors should be removed from custom field filters', function() {
46+
it('all colors should be removed from custom field filters', function () {
5147
s.removeCustomFieldFilter('foo');
5248
var expect = '["color%3Dblue"]';
5349
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
@@ -57,13 +53,11 @@ describe('settings', function() {
5753
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
5854
});
5955

60-
it('adding custom fields filter should be idempotent', function() {
56+
it('adding custom fields filter should be idempotent', function () {
6157
s.addCustomFieldFilter('city', 'helsinki');
6258
s.addCustomFieldFilter('city', 'helsinki');
6359
var expect = '["city%3Dhelsinki"]';
6460
assert.equal(JSON.stringify(s.getSettings().customFieldFilters), expect);
6561
});
66-
67-
6862
});
6963
});

‎test/throttle.js

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,30 @@ var assert = require('assert');
22
var throttle = require('../src/throttle');
33

44
function sleep(ms) {
5-
return new Promise(resolve => setTimeout(resolve, ms));
5+
return new Promise((resolve) => setTimeout(resolve, ms));
66
}
77

8-
describe('throttle', function() {
9-
10-
it('function shouldn\'t be throttled (30 function calls in 600ms)', async function() {
8+
describe('throttle', function () {
9+
it("function shouldn't be throttled (30 function calls in 600ms)", async function () {
1110
this.timeout(5000);
1211
var functionCalls = 30;
1312
var sleepTime = 20; // 30*20 = 600 ms
1413
var expectedExecutions = 30; // Function called in every iteration
1514
var executions = 0;
1615

17-
var f = function() {
16+
var f = function () {
1817
executions++;
1918
};
2019

21-
for (var i=0; i<functionCalls; i++) {
20+
for (var i = 0; i < functionCalls; i++) {
2221
f();
2322
await sleep(sleepTime);
2423
}
2524

2625
assert.equal(executions, expectedExecutions);
2726
});
2827

29-
it('function should be throttled (4 function calls in 600ms', async function() {
28+
it('function should be throttled (4 function calls in 600ms', async function () {
3029
this.timeout(5000);
3130
var functionCalls = 30;
3231
var sleepTime = 20; // 30*20 = 600 ms
@@ -37,15 +36,14 @@ describe('throttle', function() {
3736
var expectedExecutionsLowerBound = 3 + 1;
3837
var executions = 0;
3938

40-
var f = throttle(throttleDelay, function() {
39+
var f = throttle(throttleDelay, function () {
4140
executions++;
4241
});
4342

44-
for (var i=0; i<functionCalls; i++) {
43+
for (var i = 0; i < functionCalls; i++) {
4544
f();
4645
await sleep(sleepTime);
4746
}
4847
assert.equal(expectedExecutionsLowerBound <= executions, true);
4948
});
50-
5149
});

‎test/util.js

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,22 @@
11
var assert = require('assert');
22
var util = require('../src/util');
33

4-
5-
describe('util', function() {
6-
describe('isFunction', function() {
7-
it('function should be properly detected', function() {
8-
var f = function(f) { console.log(f); };
4+
describe('util', function () {
5+
describe('isFunction', function () {
6+
it('function should be properly detected', function () {
7+
var f = function (f) {
8+
console.log(f);
9+
};
910
assert.equal(util.isFunction(f), true);
1011
assert.equal(util.isFunction(console.log), true);
1112
assert.equal(util.isFunction('foo'), false);
1213
assert.equal(util.isFunction([1, 2]), false);
1314
});
14-
1515
});
1616

17-
describe('base64', function() {
18-
it('string should be encoded properly', function() {
17+
describe('base64', function () {
18+
it('string should be encoded properly', function () {
1919
assert.equal(util.base64('test'), 'dGVzdA==');
2020
});
21-
2221
});
2322
});

‎webpack.config.js

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,21 @@ module.exports = {
1919
],
2020
mode: 'production',
2121
optimization: {
22-
minimizer: [new TerserJSPlugin({
23-
extractComments: false,
24-
terserOptions: {
25-
format: {
26-
comments: /addsearch-js-client/i,
22+
minimizer: [
23+
new TerserJSPlugin({
24+
extractComments: false,
25+
terserOptions: {
26+
format: {
27+
comments: /addsearch-js-client/i
28+
}
2729
}
28-
},
29-
})]
30+
})
31+
]
3032
},
3133
resolve: {
3234
fallback: {
33-
buffer: require.resolve('buffer/'),
34-
},
35+
buffer: require.resolve('buffer/')
36+
}
3537
},
3638
module: {
3739
rules: [
@@ -41,12 +43,7 @@ module.exports = {
4143
use: {
4244
loader: 'babel-loader',
4345
options: {
44-
presets: [
45-
[
46-
'@babel/preset-env',
47-
{'targets': '> 0.1%, IE 10, not dead'}
48-
]
49-
]
46+
presets: [['@babel/preset-env', { targets: '> 0.1%, IE 10, not dead' }]]
5047
}
5148
}
5249
}

0 commit comments

Comments
 (0)
Please sign in to comment.