-
Notifications
You must be signed in to change notification settings - Fork 385
/
stored-searches.ts
83 lines (68 loc) · 1.74 KB
/
stored-searches.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import type { DocSearchHit, StoredDocSearchHit } from './types';
function isLocalStorageSupported() {
const key = '__TEST_KEY__';
try {
localStorage.setItem(key, '');
localStorage.removeItem(key);
return true;
} catch (error) {
return false;
}
}
function createStorage<TItem>(key: string) {
if (isLocalStorageSupported() === false) {
return {
setItem() {},
getItem() {
return [];
},
};
}
return {
setItem(item: TItem[]) {
return window.localStorage.setItem(key, JSON.stringify(item));
},
getItem(): TItem[] {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : [];
},
};
}
type CreateStoredSearchesOptions = {
key: string;
limit?: number;
};
export type StoredSearchPlugin<TItem> = {
add: (item: TItem) => void;
remove: (item: TItem) => void;
getAll: () => TItem[];
};
export function createStoredSearches<TItem extends StoredDocSearchHit>({
key,
limit = 5,
}: CreateStoredSearchesOptions): StoredSearchPlugin<TItem> {
const storage = createStorage<TItem>(key);
let items = storage.getItem().slice(0, limit);
return {
add(item: TItem) {
const { _highlightResult, _snippetResult, ...hit } =
item as unknown as DocSearchHit;
const isQueryAlreadySaved = items.findIndex(
(x) => x.objectID === hit.objectID
);
if (isQueryAlreadySaved > -1) {
items.splice(isQueryAlreadySaved, 1);
}
items.unshift(hit as TItem);
items = items.slice(0, limit);
storage.setItem(items);
},
remove(item: TItem) {
items = items.filter((x) => x.objectID !== item.objectID);
storage.setItem(items);
},
getAll() {
return items;
},
};
}