diff --git a/package.json b/package.json index 1febc03..693d2b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@afosto/instant-search-client", - "version": "1.0.3", + "version": "1.0.4", "private": false, "description": "The Afosto InstantSearch client", "main": "./dist/afosto-instant-search.min.js", diff --git a/src/adapters/SearchRequestAdapter.js b/src/adapters/SearchRequestAdapter.js index 8da8670..9a04509 100644 --- a/src/adapters/SearchRequestAdapter.js +++ b/src/adapters/SearchRequestAdapter.js @@ -119,6 +119,7 @@ const SearchRequestAdapter = () => { indices: [request.indexName], q: query, threshold: options.threshold || DEFAULT_OPTIONS.threshold, + session_id: request.session_id, __queryID: request.__queryID, ...pagination, }]; diff --git a/src/afostoInstantSearch.js b/src/afostoInstantSearch.js index 0a42bf5..f441067 100644 --- a/src/afostoInstantSearch.js +++ b/src/afostoInstantSearch.js @@ -1,6 +1,7 @@ import { v4 as uuid } from 'uuid'; import { SearchResponseAdapter, SearchRequestAdapter } from './adapters'; import { DEFAULT_OPTIONS } from './constants'; +import getSessionID from './utils/getSessionID'; /** * Afosto instant search client @@ -18,6 +19,7 @@ const afostoInstantSearch = (searchEngineKey, options = {}) => { const url = clientOptions.baseUrl?.replace('{key}', searchEngineKey); const searchRequestAdapter = SearchRequestAdapter(); const searchResponseAdapter = SearchResponseAdapter(); + const sessionID = getSessionID(); const getSettings = async () => { try { @@ -56,7 +58,7 @@ const afostoInstantSearch = (searchEngineKey, options = {}) => { const search = async requests => { try { - const searchRequests = requests.map(request => ({ ...request, __queryID: uuid() })); + const searchRequests = requests.map(request => ({ ...request, session_id: sessionID, __queryID: uuid() })); const searchContexts = searchRequestAdapter.transform(searchRequests, clientOptions); const [searchRequestContext] = searchContexts; diff --git a/src/constants.js b/src/constants.js index 6e32495..48a5b0a 100644 --- a/src/constants.js +++ b/src/constants.js @@ -18,3 +18,5 @@ export const OPERATOR_CONVERSION = { '<=': 'lte', '=': 'in', }; + +export const SESSION_KEY = 'afostoInstantSearch_sessionID'; diff --git a/src/utils/getSessionID.js b/src/utils/getSessionID.js new file mode 100644 index 0000000..e9b4e13 --- /dev/null +++ b/src/utils/getSessionID.js @@ -0,0 +1,21 @@ +import { v4 as uuid } from 'uuid'; +import { SESSION_KEY } from '../constants'; + +const getSessionID = () => { + const hasSessionStorage = !!window.sessionStorage; + + if (!hasSessionStorage) { + return uuid(); + } + + let sessionID = sessionStorage.getItem(SESSION_KEY); + + if (!sessionID) { + sessionID = uuid(); + sessionStorage.setItem(SESSION_KEY, sessionID); + } + + return sessionID; +}; + +export default getSessionID;