UNPKG

addsearch-js-client

Version:

AddSearch API JavaScript client

347 lines 15.1 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const apifetch_1 = __importDefault(require("./apifetch")); const indexingapi_1 = require("./indexingapi"); const stats_1 = __importDefault(require("./stats")); const ai_answers_interactions_api_1 = require("./ai-answers-interactions-api"); const settings_1 = __importDefault(require("./settings")); const util = __importStar(require("./util")); const throttle_1 = __importDefault(require("./throttle")); const cookie = __importStar(require("./cookie")); const api_1 = require("./api"); const API_HOSTNAME = 'api.addsearch.com'; const USER_TOKEN_COOKIE_NAME = 'addsearchUserToken'; class AddSearchClient { constructor(sitekey, privatekey) { this.useStatsSessionId = false; this.sitekey = sitekey; this.privatekey = privatekey || ''; this.apiHostname = API_HOSTNAME; this.statsApiHostname = API_HOSTNAME; this.settings = new settings_1.default(); this.sessionId = `a-${Math.random() * 100000000}`.substring(0, 10); this.userTokenInPersonalization = cookie.getCookie(USER_TOKEN_COOKIE_NAME) || util.generateUUID(); } search(a1, a2) { var _a; let keyword = null; let callback = null; if (typeof a1 === 'string' && typeof a2 === 'function') { keyword = a1; callback = a2; } else if (typeof a1 === 'function' && !a2) { keyword = this.settings.getSettings().keyword || null; callback = a1; } else if (this.settings.getSettings().callback) { keyword = this.settings.getSettings().keyword || null; callback = this.settings.getSettings().callback; } else { throw new Error('Illegal search parameters. Should be (keyword, callbackFunction) or (callbackFunction)'); } this.settings.setCallback(() => callback); this.settings.setKeyword(keyword); (_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); (_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); } putSentimentClick(conversationId, sentimentValue) { return (0, ai_answers_interactions_api_1.putSentimentClick)(this.apiHostname, this.sitekey, conversationId, sentimentValue); } suggestions(prefix, callback) { var _a; if (!prefix || !callback || !util.isFunction(callback)) { throw new Error('Illegal suggestions parameters. Should be (prefix, callbackFunction)'); } this.settings.setSuggestionsPrefix(prefix); (_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)) { throw new Error('Illegal autocomplete parameters. Should be (field, prefix, callbackFunction)'); } this.settings.setAutocompleteParams(field, prefix); (_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); } fetchCustomApi(field, customFilterObject, callback) { var _a; const settingsCloned = Object.assign({}, this.settings.getSettings()); settingsCloned.facetFields = (_a = settingsCloned.facetFields) === null || _a === void 0 ? void 0 : _a.filter((facetField) => field === facetField); (0, apifetch_1.default)(this.apiHostname, this.sitekey, 'search', settingsCloned, callback, null, customFilterObject); } fetchRangeFacets(options, customFilterObject, callback) { var _a; const settingsCloned = Object.assign({}, this.settings.getSettings()); (_a = settingsCloned.rangeFacets) !== null && _a !== void 0 ? _a : (settingsCloned.rangeFacets = []); settingsCloned.rangeFacets.push({ field: options.field, ranges: options.ranges }); (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)'); } (_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); } getDocument(id) { return (0, indexingapi_1.getDocument)(this.apiHostname, this.sitekey, this.privatekey, id); } saveDocument(document) { return (0, indexingapi_1.saveDocument)(this.apiHostname, this.sitekey, this.privatekey, document); } saveDocumentsBatch(batch) { if (!batch || !batch.documents || !Array.isArray(batch.documents)) { throw new Error('Please provide an array of documents: {documents: []}'); } return (0, indexingapi_1.saveDocumentsBatch)(this.apiHostname, this.sitekey, this.privatekey, batch); } deleteDocument(id) { return (0, indexingapi_1.deleteDocument)(this.apiHostname, this.sitekey, this.privatekey, id); } deleteDocumentsBatch(batch) { if (!batch || !batch.documents || !Array.isArray(batch.documents)) { throw new Error('Please provide an array of document ids: {documents: []}'); } return (0, indexingapi_1.deleteDocumentsBatch)(this.apiHostname, this.sitekey, this.privatekey, batch); } setApiHostname(hostname, conf) { if (!conf || !conf.statsApiRequestOnly) { this.apiHostname = hostname; } if (!conf || !conf.searchApiRequestOnly) { this.statsApiHostname = hostname; } } getSettings() { return this.settings.getSettings(); } setLanguage(lang) { this.settings.setLanguage(lang); } setCategoryFilters(categories) { this.settings.setCategoryFilters(categories); } addCustomFieldFilter(fieldName, value) { this.settings.addCustomFieldFilter(fieldName, value); } removeCustomFieldFilter(fieldName, value) { this.settings.removeCustomFieldFilter(fieldName, value); } setPriceRangeFilter(minCents, maxCents) { this.settings.setPriceRangeFilter(minCents, maxCents); } setDateFilter(dateFrom, dateTo) { this.settings.setDateFilter(dateFrom, dateTo); } setJWT(jwt) { this.settings.setJWT(jwt); } setUserToken(token) { this.settings.setUserToken(token); } setPaging(page, pageSize, sortBy, sortOder) { this.settings.setPaging(page, pageSize, sortBy, sortOder); } nextPage() { this.settings.nextPage(); } previousPage() { this.settings.previousPage(); } setSuggestionsSize(size) { this.settings.setSuggestionsSize(size); } setAutocompleteSize(size) { this.settings.setAutocompleteSize(size); } addFacetField(fieldName) { this.settings.addFacetField(fieldName); } addHierarchicalFacetSetting(setting) { this.settings.addHierarchicalFacetSetting(setting); } addRangeFacet(field, ranges) { this.settings.addRangeFacet(field, ranges); } addStatsField(field) { this.settings.addStatsField(field); } setNumberOfFacets(numFacets) { this.settings.setNumberOfFacets(numFacets); } setResultType(type) { this.settings.setResultType(type); } setPersonalizationEvents(events) { this.settings.setPersonalizationEvents(events); } setFilterObject(filter) { this.settings.setFilterObject(filter); } setShuffleAndLimitTo(shuffleAndLimitTo) { this.settings.setShuffleAndLimitTo(shuffleAndLimitTo); } setFuzzyMatch(fuzzy) { this.settings.setFuzzyMatch(fuzzy); } setPostfixWildcard(wildcard) { this.settings.setPostfixWildcard(wildcard); } setCacheResponseTime(cacheResponseTime) { this.settings.setCacheResponseTime(cacheResponseTime); } setCollectAnalytics(collectAnalytics) { this.settings.setCollectAnalytics(collectAnalytics); } setAnalyticsTag(tagName) { this.settings.setAnalyticsTag(tagName); } setThrottleTime(delay) { this.settings.setThrottleTime(delay); } setStatsSessionId(id) { this.sessionId = id; this.userTokenInPersonalization = id; this.useStatsSessionId = true; } getStatsSessionId() { return this.sessionId; } enableLogicalOperators(enableLogicalOperators) { this.settings.enableLogicalOperators(enableLogicalOperators); } setSearchOperator(operator) { this.settings.setSearchOperator(operator); } setApiMethod(method) { this.settings.setApiMethod(method); } sendStatsEvent(type, keyword, data) { const useUserTokenInCookie = !this.useStatsSessionId && isPersonalizationTrackingEnabled && isAddSearchCookieConsented; if (useUserTokenInCookie && !cookie.getCookie(USER_TOKEN_COOKIE_NAME)) { cookie.setCookie(USER_TOKEN_COOKIE_NAME, this.userTokenInPersonalization, personalizationCookieExpireDays); } if (type === 'search') { const payload = { action: 'search', session: useUserTokenInCookie ? this.userTokenInPersonalization : this.sessionId, keyword, numberOfResults: data.numberOfResults, tag: this.getSettings().analyticsTag }; (0, stats_1.default)(this.statsApiHostname, this.sitekey, payload, this.settings.getSettings().statsRequestIntercepted); } else if (type === 'click') { const payload = { action: 'click', session: useUserTokenInCookie ? this.userTokenInPersonalization : this.sessionId, keyword, docid: data.documentId, position: data.position, tag: this.getSettings().analyticsTag }; (0, stats_1.default)(this.statsApiHostname, this.sitekey, payload, this.settings.getSettings().statsRequestIntercepted); } else { throw new Error('Illegal sendStatsEvent type parameters. Should be search or click)'); } } getUserTokenInPersonalization() { return this.userTokenInPersonalization; } enablePersonalizationTracking(isEnabled, cookieExpireDays) { isPersonalizationTrackingEnabled = isEnabled; if (cookieExpireDays) { personalizationCookieExpireDays = cookieExpireDays; } } consentAddSearchCookie(isEnabled) { isAddSearchCookieConsented = isEnabled; } setApiRequestInterceptor(callback, option = {}) { if (typeof callback !== 'function') { console.error('API interceptor must be a function'); return; } const { searchApiRequestOnly = false, statsApiRequestOnly = false } = option; if (!searchApiRequestOnly && !statsApiRequestOnly) { (0, api_1.setRequestInterceptor)(callback, 'searchApi'); (0, api_1.setRequestInterceptor)(callback, 'statsApi'); this.settings.setStatsRequestIntercepted(true); } else { if (searchApiRequestOnly) { (0, api_1.setRequestInterceptor)(callback, 'searchApi'); } if (statsApiRequestOnly) { (0, api_1.setRequestInterceptor)(callback, 'statsApi'); this.settings.setStatsRequestIntercepted(true); } } } setCookie(cookieName, cookieValue, expireDays) { cookie.setCookie(cookieName, cookieValue, expireDays); } getCookie(cookieName) { return cookie.getCookie(cookieName); } searchResultClicked(documentId, position) { this.sendStatsEvent('click', this.settings.getSettings().keyword || '', { documentId, position }); } } let isPersonalizationTrackingEnabled = false; let isAddSearchCookieConsented = false; let personalizationCookieExpireDays = 180; module.exports = AddSearchClient; //# sourceMappingURL=index.js.map