Skip to content

Commit

Permalink
[CORE] Fixes last searches issue in SDK Personalization (#635)
Browse files Browse the repository at this point in the history
  • Loading branch information
forgiveme committed Jun 10, 2024
1 parent b41e0c9 commit b2cf5a0
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions packages/klevu-core/src/store/lastClickedProducts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { KlevuRecord } from "../models/KlevuRecord.js"
import { isBrowser } from "../utils/isBrowser.js"
import { KlevuDomEvents } from "../events/KlevuDomEvents.js"
import { KlevuConfig } from "../config.js"
import { KlevuStorage } from "../utils/storage.js"
import { KlevuStorage, StorageType } from "../utils/storage.js"

const ONE_HOUR = 36000000
export const LAST_CLICKED_STORAGE_KEY = "klevu-last-clicks"

export const LAST_CLICKED_CATEGORY_STORAGE_KEY = "klevu-last-clicks-cat"
const MAX_COUNT = 20
/**
* Keeps track of last clicked products in store
*/
Expand Down Expand Up @@ -36,6 +37,18 @@ class LastClickedProducts {
)
}
}
private saveCat() {
if (KlevuConfig.getDefault().disableClickTracking) {
return
}
if (isBrowser() && window.sessionStorage) {
KlevuStorage.setItem(
LAST_CLICKED_CATEGORY_STORAGE_KEY,
JSON.stringify(this.categoryCache),
StorageType.SESSION
)
}
}

private restore() {
if (isBrowser() && window.localStorage) {
Expand All @@ -44,6 +57,15 @@ class LastClickedProducts {
this.clicks = JSON.parse(res)
}
}
if (isBrowser() && window.sessionStorage) {
const resCat = KlevuStorage.getItem(
LAST_CLICKED_CATEGORY_STORAGE_KEY,
StorageType.SESSION
)
if (resCat) {
this.categoryCache = JSON.parse(resCat)
}
}
}

constructor() {
Expand All @@ -60,13 +82,19 @@ class LastClickedProducts {
if (KlevuConfig.getDefault().disableClickTracking) {
return
}
const lastIndex = this.clicks.findIndex((ls) => ls.id === productId)

if (lastIndex > -1) {
this.clicks.splice(lastIndex, 1)
}
this.clicks.push({
ts: new Date(),
id: productId,
product,
})

if (this.clicks.length > MAX_COUNT) {
this.clicks = this.clicks.slice(MAX_COUNT * -1)
}
this.save()

if (isBrowser()) {
Expand Down Expand Up @@ -159,7 +187,9 @@ class LastClickedProducts {
cached: new Date(),
ids,
}
KlevuStorage.addKey(LAST_CLICKED_CATEGORY_STORAGE_KEY)

this.saveCat()
return ids
}
}
Expand Down

0 comments on commit b2cf5a0

Please sign in to comment.