-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathgetter.js
More file actions
156 lines (141 loc) · 5.4 KB
/
getter.js
File metadata and controls
156 lines (141 loc) · 5.4 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { log, canUseCache } from './utils.js'
var db
function openCache(config) {
if (config.cache && typeof window !== 'undefined') {
const request = window.indexedDB.open("pokeapi-js-wrapper", 8);
return new Promise((resolve, reject) => {
request.onerror = (event) => {
log('IndexedDB not available')
reject()
}
request.onupgradeneeded = (event) => {
const db = event.target.result;
const transaction = event.target.transaction;
let objectStore;
if (!db.objectStoreNames.contains('cache')) {
objectStore = db.createObjectStore("cache", { autoIncrement: false });
log('Object store "cache" created');
} else {
objectStore = transaction.objectStore("cache");
}
if (!objectStore.indexNames.contains("deploy_date_index")) {
objectStore.createIndex("deploy_date_index", "meta.deploy_date", { unique: false });
log('Index "deploy_date_index" created');
}
}
request.onsuccess = (event) => {
db = event.target.result;
log('db opened')
resolve(db)
}
request.onversionchange = (event) => {
db.close()
reject()
}
request.onblocked = (event) => {
db.close()
reject()
}
});
}
}
function getFromDB(objectStore, url) {
return new Promise((resolve, reject) => {
const cachedObject = objectStore.get(url)
cachedObject.onsuccess = () => resolve(cachedObject.result);
cachedObject.onerror = () => reject(cachedObject.error);
});
}
async function loadResource(config, url) {
if (! url.includes('://')) {
if (url.startsWith('/api/v2/')) {
url = `${config.protocol}://${config.hostName}${url}`
} else if (!url.includes('://')) {
url = `${config.protocol}://${config.hostName}${config.versionPath}${url}`
}
}
if (canUseCache(config, db)) {
const transaction = db.transaction("cache", "readonly");
const objectStore = transaction.objectStore("cache");
const data = await getFromDB(objectStore, url);
if (data) {
log(`read from cache ${url}`)
return data
} else {
return await loadUrl(config, url)
}
} else {
return await loadUrl(config, url)
}
}
async function loadUrl(config, url) {
const response = await fetch(url);
const body = await response.json()
if (response.status === 200) {
if (canUseCache(config, db)) {
const deploy_date = parseInt(response.headers.get('X-PokeAPI-Deploy-Date'))
body.meta = { deploy_date }
const transaction = db.transaction("cache", "readwrite");
const objectStore = transaction.objectStore("cache");
const request = objectStore.add(body, url)
request.onsuccess = () => {
log(`object cached ${url}`);
}
request.onerror = () => {
log(request.error)
}
}
}
return body
}
function sizeCache(config) {
if (canUseCache(config, db)) {
return new Promise((resolve, reject) => {
const transaction = db.transaction("cache", "readwrite");
const objectStore = transaction.objectStore("cache");
const request = objectStore.count()
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} else {
return Promise.reject(new Error('Cache not available'))
}
}
async function invalidateCache(config) {
if (canUseCache(config, db)) {
const meta = await loadResource({ ...config, cache: false }, 'meta');
const upstream_deploy_date = parseInt(meta.deploy_date);
return new Promise((resolve, reject) => {
const transaction = db.transaction("cache", "readwrite");
const objectStore = transaction.objectStore("cache");
const index = objectStore.index("deploy_date_index");
const range = IDBKeyRange.upperBound(upstream_deploy_date, true);
const request = index.getAllKeys(range);
request.onsuccess = () => {
const keys = request.result;
keys.forEach(pk => {
objectStore.delete(pk);
log(`invalidated ${pk}`);
});
resolve(true);
};
request.onerror = () => reject(new Error(request.error));
});
} else {
throw new Error('cache not available');
}
}
function clearCache(config) {
if (canUseCache(config, db)) {
return new Promise((resolve, reject) => {
const transaction = db.transaction("cache", "readwrite");
const objectStore = transaction.objectStore("cache");
const request = objectStore.clear()
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} else {
return Promise.reject(new Error('Cache not available'))
}
}
export { loadResource, openCache, sizeCache, clearCache, invalidateCache }