-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathserverapi_localstorage.js
103 lines (78 loc) · 2.54 KB
/
serverapi_localstorage.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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* ServerAPI mockup - backed by localStorage for demo purposes only.
*
* Not efficient for large data because of localStorage limitations.
*/
import axios from "axios"
const KEY = "movies";
class LocalStorageAPI {
constructor() {
}
query_movies() {
return new Promise((resolve, reject) => {
//localStorage.removeItem("movies") // to remove all
var value = localStorage.getItem(KEY);
if (!value) {
// load initial data
let url = "/static/exampledata/movies.json";
axios.get(url)
.then(reply => {
localStorage.setItem(KEY, JSON.stringify(reply.data));
resolve(reply.data);
});
} else {
let data = JSON.parse(value);
resolve(data);
}
})
}
get_movie(id) {
return new Promise((resolve, reject) => {
id = parseInt(id);
var value = localStorage.getItem(KEY);
let data = JSON.parse(value) || [];
// search for id
for (const x of data) {
if (x.id == id) {
resolve(x);
return;
}
}
reject();
});
}
save_movie(item) {
return new Promise((resolve, reject) => {
var value = localStorage.getItem(KEY);
let moviearray = JSON.parse(value);
if (!item.id) {
// create object
const seconds = Math.floor(Date.now() / 1000);
item.id = seconds;
moviearray.push(item);
} else {
// edit object
for (const x of moviearray) {
if (x.id == item.id) {
x.title = item.title;
x.director = item.director;
}
}
}
localStorage.setItem(KEY, JSON.stringify(moviearray));
resolve(item);
})
}
delete_movie(id) {
return new Promise((resolve, reject) => {
id = parseInt(id);
var value = localStorage.getItem(KEY);
let moviearray = JSON.parse(value);
moviearray = moviearray.filter(item => item.id !== id)
localStorage.setItem(KEY, JSON.stringify(moviearray));
resolve();
})
}
}
// export singleton object
const api_mockup = new LocalStorageAPI();
export default api_mockup;