addsearch-js-client
Advanced tools
Comparing version
@@ -5,2 +5,3 @@ "use strict"; | ||
const api_1 = require("./api"); | ||
const util_1 = require("./util"); | ||
/* eslint-enable @typescript-eslint/no-explicit-any */ | ||
@@ -11,2 +12,3 @@ /** | ||
const executeApiFetch = function (apiHostname, sitekey, type, settings, cb, fuzzyRetry, customFilterObject, recommendOptions) { | ||
var _a, _b, _c, _d, _e, _f, _g, _h; | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
@@ -33,2 +35,3 @@ const settingToQueryParam = function (setting, key) { | ||
let queryParamsString = ''; | ||
let requestPayloadObject = {}; | ||
// API Path (eq. /search, /suggest, /autocomplete/document-field) | ||
@@ -61,2 +64,3 @@ let apiEndpoint = null; | ||
} | ||
// GET Parameters | ||
queryParamsString = | ||
@@ -82,4 +86,12 @@ settingToQueryParam(settings === null || settings === void 0 ? void 0 : settings.lang, 'lang') + | ||
settingToQueryParam(settings === null || settings === void 0 ? void 0 : settings.analyticsTag, 'analyticsTag'); | ||
// POST Parameters | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { language: settings === null || settings === void 0 ? void 0 : settings.lang, fuzzy: fuzzy !== true && fuzzy !== false ? fuzzy : JSON.stringify(fuzzy), collectAnalytics: settings === null || settings === void 0 ? void 0 : settings.collectAnalytics, postfixWildcard: settings === null || settings === void 0 ? void 0 : settings.postfixWildcard, categories: (settings === null || settings === void 0 ? void 0 : settings.categories) ? settings === null || settings === void 0 ? void 0 : settings.categories.split(',') : undefined, priceFromCents: (settings === null || settings === void 0 ? void 0 : settings.priceFromCents) ? parseInt(settings === null || settings === void 0 ? void 0 : settings.priceFromCents, 10) : undefined, priceToCents: (settings === null || settings === void 0 ? void 0 : settings.priceToCents) ? parseInt(settings === null || settings === void 0 ? void 0 : settings.priceToCents, 10) : undefined, dateFrom: settings === null || settings === void 0 ? void 0 : settings.dateFrom, dateTo: settings === null || settings === void 0 ? void 0 : settings.dateTo, paging: { | ||
page: (_a = settings === null || settings === void 0 ? void 0 : settings.paging.page) !== null && _a !== void 0 ? _a : 1, | ||
pageSize: (_b = settings === null || settings === void 0 ? void 0 : settings.paging.pageSize) !== null && _b !== void 0 ? _b : 10, | ||
shuffleAndLimitTo: (_c = settings === null || settings === void 0 ? void 0 : settings.shuffleAndLimitTo) !== null && _c !== void 0 ? _c : undefined, | ||
sortByField: settings === null || settings === void 0 ? void 0 : settings.paging.sortBy, | ||
sortOrder: settings === null || settings === void 0 ? void 0 : settings.paging.sortOrder | ||
}, jwt: settings === null || settings === void 0 ? void 0 : settings.jwt, resultType: settings === null || settings === void 0 ? void 0 : settings.resultType, userToken: (_d = settings === null || settings === void 0 ? void 0 : settings.userToken) !== null && _d !== void 0 ? _d : undefined, numFacets: settings === null || settings === void 0 ? void 0 : settings.numFacets, cacheResponseWithTtlSeconds: (_e = settings === null || settings === void 0 ? void 0 : settings.cacheResponseTime) !== null && _e !== void 0 ? _e : undefined, defaultOperator: (_f = settings === null || settings === void 0 ? void 0 : settings.searchOperator) !== null && _f !== void 0 ? _f : undefined, analyticsTag: settings === null || settings === void 0 ? void 0 : settings.analyticsTag }); | ||
// Add sortBy and sortOrder | ||
if (Array.isArray(settings === null || settings === void 0 ? void 0 : settings.paging.sortBy)) { | ||
if (Array.isArray(settings === null || settings === void 0 ? void 0 : settings.paging.sortBy) && (settings === null || settings === void 0 ? void 0 : settings.paging.sortBy.length) > 1) { | ||
settings === null || settings === void 0 ? void 0 : settings.paging.sortBy.forEach(function (value, index) { | ||
@@ -100,11 +112,21 @@ queryParamsString = | ||
if (settings === null || settings === void 0 ? void 0 : settings.customFieldFilters) { | ||
const customFieldFiltersValues = {}; | ||
for (let i = 0; i < (settings === null || settings === void 0 ? void 0 : settings.customFieldFilters.length); i++) { | ||
queryParamsString = queryParamsString + '&customField=' + (settings === null || settings === void 0 ? void 0 : settings.customFieldFilters[i]); | ||
const decodedCustomFieldFilter = decodeURIComponent(settings === null || settings === void 0 ? void 0 : settings.customFieldFilters[i]); | ||
const customFieldFilterPair = decodedCustomFieldFilter.split('='); | ||
const customFieldName = customFieldFilterPair[0]; | ||
const customFieldValue = customFieldFilterPair[1]; | ||
customFieldFiltersValues[customFieldName] = customFieldValue; | ||
} | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { customField: (0, util_1.isEmptyObject)(customFieldFiltersValues) ? undefined : customFieldFiltersValues }); | ||
} | ||
// Add facet fields | ||
if (settings === null || settings === void 0 ? void 0 : settings.facetFields) { | ||
const facetFieldsValues = []; | ||
for (let i = 0; i < (settings === null || settings === void 0 ? void 0 : settings.facetFields.length); i++) { | ||
queryParamsString = queryParamsString + '&facet=' + (settings === null || settings === void 0 ? void 0 : settings.facetFields[i]); | ||
facetFieldsValues.push(settings === null || settings === void 0 ? void 0 : settings.facetFields[i]); | ||
} | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { facet: facetFieldsValues.length > 0 ? facetFieldsValues : undefined }); | ||
} | ||
@@ -117,2 +139,3 @@ // Range facets | ||
encodeURIComponent(JSON.stringify(settings === null || settings === void 0 ? void 0 : settings.rangeFacets)); | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { rangeFacets: settings === null || settings === void 0 ? void 0 : settings.rangeFacets }); | ||
} | ||
@@ -125,11 +148,16 @@ // Hierarchical facets | ||
encodeURIComponent(JSON.stringify(settings === null || settings === void 0 ? void 0 : settings.hierarchicalFacetSetting)); | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { hierarchicalFacets: settings === null || settings === void 0 ? void 0 : settings.hierarchicalFacetSetting }); | ||
} | ||
// Stats fields | ||
if (settings === null || settings === void 0 ? void 0 : settings.statsFields) { | ||
const statsFieldsValues = []; | ||
for (let i = 0; i < (settings === null || settings === void 0 ? void 0 : settings.statsFields.length); i++) { | ||
queryParamsString = queryParamsString + '&fieldStat=' + (settings === null || settings === void 0 ? void 0 : settings.statsFields[i]); | ||
statsFieldsValues.push(settings === null || settings === void 0 ? void 0 : settings.statsFields[i]); | ||
} | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { statsFields: statsFieldsValues }); | ||
} | ||
// Personalization events | ||
if ((settings === null || settings === void 0 ? void 0 : settings.personalizationEvents) && Array.isArray(settings === null || settings === void 0 ? void 0 : settings.personalizationEvents)) { | ||
const personalizationEventsValues = []; | ||
for (let i = 0; i < (settings === null || settings === void 0 ? void 0 : settings.personalizationEvents.length); i++) { | ||
@@ -140,3 +168,5 @@ const obj = settings === null || settings === void 0 ? void 0 : settings.personalizationEvents[i]; | ||
queryParamsString + '&personalizationEvent=' + encodeURIComponent(key + '=' + obj[key]); | ||
personalizationEventsValues.push(obj); | ||
} | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { personalizationEvents: personalizationEventsValues }); | ||
} | ||
@@ -147,2 +177,3 @@ // Filter object | ||
queryParamsString + '&filter=' + encodeURIComponent(JSON.stringify(customFilterObject)); | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { filter: customFilterObject }); | ||
} | ||
@@ -152,2 +183,3 @@ else if (settings === null || settings === void 0 ? void 0 : settings.filterObject) { | ||
queryParamsString + '&filter=' + encodeURIComponent(JSON.stringify(settings === null || settings === void 0 ? void 0 : settings.filterObject)); | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { filter: (0, util_1.isEmptyObject)(settings === null || settings === void 0 ? void 0 : settings.filterObject) ? undefined : settings === null || settings === void 0 ? void 0 : settings.filterObject }); | ||
} | ||
@@ -201,2 +233,3 @@ apiEndpoint = | ||
settingToQueryParam(settings === null || settings === void 0 ? void 0 : settings.lang, 'language'); | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { size: settings === null || settings === void 0 ? void 0 : settings.suggestionsSize, language: settings === null || settings === void 0 ? void 0 : settings.lang }); | ||
keyword = settings === null || settings === void 0 ? void 0 : settings.suggestionsPrefix; | ||
@@ -231,2 +264,3 @@ apiEndpoint = | ||
queryParamsString; | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { source: settings === null || settings === void 0 ? void 0 : settings.autocomplete.field, size: settings === null || settings === void 0 ? void 0 : settings.autocomplete.size }); | ||
} | ||
@@ -243,2 +277,3 @@ else if (type === 'recommend') { | ||
queryParamsString; | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { itemId: (_g = recommendOptions.itemId) !== null && _g !== void 0 ? _g : undefined, blockId: recommendOptions.blockId }); | ||
} | ||
@@ -253,9 +288,9 @@ else if ((recommendOptions === null || recommendOptions === void 0 ? void 0 : recommendOptions.type) === 'FREQUENTLY_BOUGHT_TOGETHER') { | ||
queryParamsString; | ||
requestPayloadObject = Object.assign(Object.assign({}, requestPayloadObject), { itemId: (_h = recommendOptions.itemId) !== null && _h !== void 0 ? _h : undefined, configurationKey: recommendOptions.configurationKey }); | ||
} | ||
apiEndpoint = 'https://' + apiHostname + '/v1/' + apiPath; | ||
} | ||
// Handle API response for all types except ai-answers | ||
if (type !== 'ai-answers') { | ||
api_1.apiInstance | ||
.get(apiEndpoint) | ||
.then(function (response) { | ||
const handleApiResponse = function (response) { | ||
var _a, _b, _c; | ||
@@ -270,3 +305,2 @@ const json = response.data; | ||
} | ||
// Fuzzy not "retry" OR fuzzyRetry already returning | ||
else { | ||
@@ -280,4 +314,4 @@ // Cap fuzzy results to one page as quality decreases quickly | ||
} | ||
}) | ||
.catch(function (error) { | ||
}; | ||
const handleApiError = function (error) { | ||
console.error(error); | ||
@@ -290,3 +324,18 @@ cb({ | ||
}); | ||
}); | ||
}; | ||
if ((settings === null || settings === void 0 ? void 0 : settings.apiMethod) === 'POST' && ['search', 'suggest', 'autocomplete'].includes(type)) { | ||
apiEndpoint = 'https://' + apiHostname + '/v1/' + apiPath + '/' + sitekey; | ||
const term = type === 'search' ? decodeURIComponent(keyword) : keyword; | ||
requestPayloadObject = Object.assign({ term }, requestPayloadObject); | ||
api_1.apiInstance | ||
.post(apiEndpoint, requestPayloadObject) | ||
.then(handleApiResponse) | ||
.catch(handleApiError); | ||
} | ||
else { | ||
api_1.apiInstance | ||
.get(apiEndpoint) | ||
.then(handleApiResponse) | ||
.catch(handleApiError); | ||
} | ||
} | ||
@@ -293,0 +342,0 @@ }; |
@@ -62,2 +62,3 @@ "use strict"; | ||
search(a1, a2) { | ||
var _a; | ||
let keyword = null; | ||
@@ -82,13 +83,10 @@ let callback = null; | ||
this.settings.setKeyword(keyword); | ||
if (!this.throttledSearchFetch) { | ||
this.throttledSearchFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default); | ||
} | ||
(_a = this.throttledSearchFetch) !== null && _a !== void 0 ? _a : (this.throttledSearchFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default)); | ||
this.throttledSearchFetch(this.apiHostname, this.sitekey, 'search', this.settings.getSettings(), callback); | ||
} | ||
aiAnswers(keyword, callback) { | ||
var _a; | ||
this.settings.setCallback(() => callback); | ||
this.settings.setKeyword(keyword); | ||
if (!this.throttledAiAnswersFetch) { | ||
this.throttledAiAnswersFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default); | ||
} | ||
(_a = this.throttledAiAnswersFetch) !== null && _a !== void 0 ? _a : (this.throttledAiAnswersFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default)); | ||
this.throttledAiAnswersFetch(this.apiHostname, this.sitekey, 'ai-answers', this.settings.getSettings(), callback); | ||
@@ -100,2 +98,3 @@ } | ||
suggestions(prefix, callback) { | ||
var _a; | ||
if (!prefix || !callback || !util.isFunction(callback)) { | ||
@@ -105,8 +104,7 @@ throw new Error('Illegal suggestions parameters. Should be (prefix, callbackFunction)'); | ||
this.settings.setSuggestionsPrefix(prefix); | ||
if (!this.throttledSuggestionsFetch) { | ||
this.throttledSuggestionsFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default); | ||
} | ||
(_a = this.throttledSuggestionsFetch) !== null && _a !== void 0 ? _a : (this.throttledSuggestionsFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default)); | ||
this.throttledSuggestionsFetch(this.apiHostname, this.sitekey, 'suggest', this.settings.getSettings(), callback); | ||
} | ||
autocomplete(field, prefix, callback) { | ||
var _a; | ||
if (!field || !prefix || !callback || !util.isFunction(callback)) { | ||
@@ -116,5 +114,3 @@ throw new Error('Illegal autocomplete parameters. Should be (field, prefix, callbackFunction)'); | ||
this.settings.setAutocompleteParams(field, prefix); | ||
if (!this.throttledAutocompleteFetch) { | ||
this.throttledAutocompleteFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default); | ||
} | ||
(_a = this.throttledAutocompleteFetch) !== null && _a !== void 0 ? _a : (this.throttledAutocompleteFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default)); | ||
this.throttledAutocompleteFetch(this.apiHostname, this.sitekey, 'autocomplete', this.settings.getSettings(), callback); | ||
@@ -129,6 +125,5 @@ } | ||
fetchRangeFacets(options, customFilterObject, callback) { | ||
var _a; | ||
const settingsCloned = Object.assign({}, this.settings.getSettings()); | ||
if (!settingsCloned.rangeFacets) { | ||
settingsCloned.rangeFacets = []; | ||
} | ||
(_a = settingsCloned.rangeFacets) !== null && _a !== void 0 ? _a : (settingsCloned.rangeFacets = []); | ||
settingsCloned.rangeFacets.push({ field: options.field, ranges: options.ranges }); | ||
@@ -138,9 +133,8 @@ (0, apifetch_1.default)(this.apiHostname, this.sitekey, 'search', settingsCloned, callback, null, customFilterObject); | ||
recommendations(options, callback) { | ||
var _a; | ||
if (!options || !callback || !util.isFunction(callback)) { | ||
throw new Error('Illegal recommendations parameters. Should be (options, callbackFunction)'); | ||
} | ||
if (!this.throttledRecommendationFetch) { | ||
this.throttledRecommendationFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default); | ||
} | ||
this.throttledRecommendationFetch(this.apiHostname, this.sitekey, 'recommend', null, callback, false, null, options); | ||
(_a = this.throttledRecommendationFetch) !== null && _a !== void 0 ? _a : (this.throttledRecommendationFetch = (0, throttle_1.default)(this.settings.getSettings().throttleTimeMs, apifetch_1.default)); | ||
this.throttledRecommendationFetch(this.apiHostname, this.sitekey, 'recommend', this.settings.getSettings(), callback, false, null, options); | ||
} | ||
@@ -277,2 +271,5 @@ getDocument(id) { | ||
} | ||
setApiMethod(method) { | ||
this.settings.setApiMethod(method); | ||
} | ||
sendStatsEvent(type, keyword, data) { | ||
@@ -279,0 +276,0 @@ const useUserTokenInCookie = !this.useStatsSessionId && isPersonalizationTrackingEnabled && isAddSearchCookieConsented; |
@@ -27,3 +27,4 @@ "use strict"; | ||
cacheResponseTime: null, | ||
statsRequestIntercepted: false | ||
statsRequestIntercepted: false, | ||
apiMethod: 'GET' | ||
}; | ||
@@ -149,11 +150,11 @@ } | ||
addRangeFacet(field, ranges) { | ||
if (!this.settings.rangeFacets) { | ||
this.settings.rangeFacets = []; | ||
} | ||
var _a; | ||
var _b; | ||
(_a = (_b = this.settings).rangeFacets) !== null && _a !== void 0 ? _a : (_b.rangeFacets = []); | ||
this.settings.rangeFacets.push({ field, ranges }); | ||
} | ||
addStatsField(field) { | ||
if (!this.settings.statsFields) { | ||
this.settings.statsFields = []; | ||
} | ||
var _a; | ||
var _b; | ||
(_a = (_b = this.settings).statsFields) !== null && _a !== void 0 ? _a : (_b.statsFields = []); | ||
if (!this.settings.statsFields.includes(field)) { | ||
@@ -190,4 +191,10 @@ this.settings.statsFields.push(field); | ||
} | ||
setApiMethod(method) { | ||
if (method !== 'GET' && method !== 'POST') { | ||
throw new Error("API method must be 'GET' or 'POST'"); | ||
} | ||
this.settings.apiMethod = method; | ||
} | ||
} | ||
exports.default = SettingsManager; | ||
//# sourceMappingURL=settings.js.map |
import { ApiFetchCallback, SuggestionsResponse } from './apifetch'; | ||
import { Settings, PersonalizationEvent, SearchOperator, SortByOptions, SortOrderOptions, FromToRange, FuzzyMatch } from './settings'; | ||
import { Settings, PersonalizationEvent, SearchOperator, SortByOptions, SortOrderOptions, FromToRange, FuzzyMatch, ApiMethod } from './settings'; | ||
import { RequestInterceptorCallback } from './api'; | ||
@@ -97,2 +97,3 @@ interface RangeFacetOption { | ||
setSearchOperator(operator: SearchOperator): void; | ||
setApiMethod(method: ApiMethod): void; | ||
sendStatsEvent(type: 'search' | 'click', keyword: string, data: StatsEventPayload): void; | ||
@@ -99,0 +100,0 @@ getUserTokenInPersonalization(): string; |
@@ -65,3 +65,5 @@ export type SortOrder = 'asc' | 'desc'; | ||
shuffleAndLimitTo?: number; | ||
apiMethod?: ApiMethod; | ||
}; | ||
export type ApiMethod = 'GET' | 'POST'; | ||
declare class SettingsManager { | ||
@@ -106,4 +108,5 @@ private settings; | ||
setStatsRequestIntercepted(isIntercepted: boolean): void; | ||
setApiMethod(method: ApiMethod): void; | ||
} | ||
export default SettingsManager; | ||
//# sourceMappingURL=settings.d.ts.map |
@@ -6,3 +6,4 @@ import { SortByOptions, SortOrderOptions } from './settings'; | ||
declare const generateUUID: () => string; | ||
export { isFunction, base64, validateSetPagingParams, generateUUID }; | ||
declare const isEmptyObject: (obj: unknown) => boolean; | ||
export { isFunction, base64, validateSetPagingParams, generateUUID, isEmptyObject }; | ||
//# sourceMappingURL=util.d.ts.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.generateUUID = exports.validateSetPagingParams = exports.base64 = exports.isFunction = void 0; | ||
exports.isEmptyObject = exports.generateUUID = exports.validateSetPagingParams = exports.base64 = exports.isFunction = void 0; | ||
const buffer_1 = require("buffer/"); | ||
@@ -49,2 +49,12 @@ const uuid_1 = require("uuid"); | ||
exports.generateUUID = generateUUID; | ||
const isEmptyObject = (obj) => { | ||
if (obj == null) { | ||
return true; | ||
} | ||
if (Array.isArray(obj) || Object.prototype.toString.call(obj) !== '[object Object]') { | ||
return true; | ||
} | ||
return Object.keys(obj).length === 0; | ||
}; | ||
exports.isEmptyObject = isEmptyObject; | ||
//# sourceMappingURL=util.js.map |
{ | ||
"name": "addsearch-js-client", | ||
"version": "1.0.5", | ||
"version": "1.1.0", | ||
"description": "AddSearch API JavaScript client", | ||
@@ -5,0 +5,0 @@ "repository": { |
@@ -535,2 +535,12 @@ # AddSearch Search API Client for JavaScript | ||
## POST API | ||
:exclamation: POST API is not fully supported. If you need to use some methods in the library, please contact our support. | ||
#### Fetch AI answers | ||
```js | ||
// default method: "GET" | ||
client.setApiMethod('POST'); | ||
``` | ||
## Indexing API | ||
@@ -537,0 +547,0 @@ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
259603
6.91%1567
4.89%785
1.29%