-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLocalStorageAdapter.js
56 lines (51 loc) · 1.5 KB
/
LocalStorageAdapter.js
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
/** */
export default class LocalStorageAdapter {
/** */
constructor(annotationPageId) {
this.annotationPageId = annotationPageId;
}
/** */
async create(annotation) {
const emptyAnnoPage = {
id: this.annotationPageId,
items: [],
type: 'AnnotationPage',
};
const annotationPage = await this.all() || emptyAnnoPage;
annotationPage.items.push(annotation);
localStorage.setItem(this.annotationPageId, JSON.stringify(annotationPage));
return annotationPage;
}
/** */
async update(annotation) {
const annotationPage = await this.all();
if (annotationPage) {
const currentIndex = annotationPage.items.findIndex((item) => item.id === annotation.id);
annotationPage.items.splice(currentIndex, 1, annotation);
localStorage.setItem(this.annotationPageId, JSON.stringify(annotationPage));
return annotationPage;
}
return null;
}
/** */
async delete(annoId) {
const annotationPage = await this.all();
if (annotationPage) {
annotationPage.items = annotationPage.items.filter((item) => item.id !== annoId);
}
localStorage.setItem(this.annotationPageId, JSON.stringify(annotationPage));
return annotationPage;
}
/** */
async get(annoId) {
const annotationPage = await this.all();
if (annotationPage) {
return annotationPage.items.find((item) => item.id === annoId);
}
return null;
}
/** */
async all() {
return JSON.parse(localStorage.getItem(this.annotationPageId));
}
}