forked from carcer/sticky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsticky-0.3.js
360 lines (325 loc) · 10.1 KB
/
sticky-0.3.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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/**
* Sticky
*
* Version 0.3
* Copyright 2011 Alexander C. Mingoia
* MIT Licensed
*
* Simple JavaScript HTML5 browser storage cache.
* Persists to memory, indexedDB, webSQL, localStorage, globalStorage, and cookies.
*
* Objects and arrays are stringified before storage in WebDB, localStorage, or cookies.
* Strings longer than 128 characters aren't persisted to cookies.
*
* WebSQL (SQLite)
* Chrome 4+, Opera 10.5+, Safari 3.1+, and Android Browser 2.1+
* 5MB of data per DB, but can request more
* IndexedDB
* IE 10+, FireFox 4+, and Chrome 11+
* localStorage
* Safari 4+, Mobile Safari (iPhone/iPad), Firefox 3.5+, Internet Explorer 8+ and Chrome 4+
* 5MB of data per domain
* globalStorage
* FireFox 2-3
* Cookies
* Maximum size varies across implementations
*
* For more compatibility information, see: http://caniuse.com/
*/
/**
* Constructor
*
* @param {Map} opts Options:
* var options = {
* name: 'Store A' // A name for this store that acts as a unique identifier.
* // You need to set this if you're going to have multiple stores.
* domain: 'example.com', // Custom cookie domain
* expires: 168, // Cookie expiration in hours
* ready: function() {}, // Fires after repopulating cache
* size: 10, // WebSQL database size in megabytes
* version: '1.0' // Version for this store
* };
*
* @return {StickyStore} Returns an instantiated store object
*/
function StickyStore(opts) {
// Default options
if (!opts) opts = {};
if (!opts.domain) opts.domain = window.location.hostname;
if (!opts.expires) opts.expires = 24*7; // Cookie expiration in hours
if (!opts.name) opts.name = 'sticky';
if (!opts.size) opts.size = 5; // Size in MB
if (!opts.version) opts.version = '0.3'; // Version for DB
if (opts.ready && typeof opts.ready !== 'function') {
throw new Error('opts.ready must be a function');
}
this.opts = opts;
this.cache = {}; // Memory cache container object
this.SQLite; // WebDB connection object
this.indexedDB // Indexed DB request object
// Wrap localStorage and globalStorage
if (window.localStorage) {
this.storage = window.localStorage;
}
else if (window.globalStorage) {
this.storage = window.globalStorage[opts.domain];
}
// Needed to keep context in async methods
var store = this;
// Initialize IndexedDB and repopulate cache
if (window.indexedDB) {
// Request DB
var request = window.indexedDB.open(opts.name, 'Sticky Offline Web Cache');
request.onsuccess = function(event) {
store.indexedDB = event.result;
// If version is different, we need to set version
// and create an object store
if (store.indexedDB.version != opts.version) {
var request = store.indexedDB.setVersion(opts.version);
request.onsuccess = function(event) {
// Create our object store for cached data
var objectStore = db.createObjectStore('cache', {'keyPath': 'key'});
opts.ready && opts.ready.call(store);
};
request.onerror = function(event) {
console.log('Sticky Error: ' + request.errorCode);
opts.ready && opts.ready.call(store);
};
}
else {
var objectStore = store.indexedDB.transaction('cache').objectStore('cache');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
// Only load records for this specific store
if (cursor && cursor.key.indexOf(opts.name + opts.version) === 0) {
if (cursor.value.data.substr(0, 4) === 'J::O') {
try {
var item = JSON.parse(cursor.value.data.substr(4));
store.set(cursor.key, item);
}
catch (err) {
console.log('Sticky Error: ' + err);
}
}
else {
store.set(cursor.key, cursor.value.data);
}
cursor['continue']();
}
else {
opts.ready && opts.ready.call(store);
}
}
}
}
request.onerror = function(event) {
console.log('Sticky Error: ' + request.errorCode);
opts.ready && opts.ready.call(store);
}
}
// Initialize WebDB and repopulate cache
else if (window.openDatabase) {
// Try and open DB
try {
this.SQLite = window.openDatabase(opts.name, opts.version, 'Sticky Offline Web Cache', (opts.size * 1024 * 1024));
if (this.SQLite) {
this.SQLite.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS cache (key TEXT, data TEXT)');
// Repopulate cache container object with data stored in SQLite
tx.executeSql('SELECT * FROM cache', [], function(tx, results) {
if (results.rows.length > 0) {
for (var i=0; i<results.rows.length; i++) {
var record = results.rows.item(i);
// Only load records for this specific store
if (record['key'].indexOf(opts.name + opts.version) === 0) {
if (record['data'] && record['data'].substr(0, 4) === 'J::O') {
try {
var item = JSON.parse(record['data'].substr(4));
store.set(record['key'], item);
}
catch (err) {
console.log('Sticky Error: ' + err);
}
}
else {
store.set(record['key'], record['data']);
}
}
}
opts.ready && opts.ready.call(store);
}
else {
opts.ready && opts.ready.call(store);
}
});
});
}
}
catch (err) {
console.log('Sticky Warning: ' + err);
}
}
else {
opts.ready && opts.ready.call(store);
}
};
/**
* Set
*
* @param String key
* @param Mixed value
*
* @return Mixed Returns reference to stored value or false for failure or error
*/
StickyStore.prototype.set = (function(key, item) {
if (!item) return false;
// Prefix key with store name/identifier
key = this.opts.name + this.opts.version + key;
var value;
var itemType = typeof item;
// Store item in memory cache
this.cache[key] = item;
// Objects and arrays are stringified, and aren't stored in cookies (they're too big)
if (itemType === 'object' || itemType === 'array') {
try {
value = 'J::O' + JSON.stringify(item);
}
catch (err) {
console.log('Sticky Error: ' + err);
}
}
else if (itemType === 'string') {
value = item;
}
if (value) {
// Only string values less than 128 characters get stored in cookies
if (value.length < 128) {
document.cookie = key + '=' + value
+ '; expires=' + new Date(new Date().getTime() + (this.opts.expires*60*60*1000)).toGMTString()
+ '; domain=' + this.opts.domain
+ '; path=/';
}
// Copy value to localStorage or globalStorage
if (this.storage) {
try {
this.storage.setItem(key, value);
}
catch (err) {
console.log('Sticky Error: ' + err);
}
}
// Copy value to webDB
if (this.SQLite) {
// Try insert first
var insert = function(tx, error) {
if (error && error.rowsAffected === 0) {
tx.executeSql('INSERT INTO cache (key, data) VALUES (?, ?)', [key, value]);
}
}
// Update if insert fails
var update = function(tx) {
tx.executeSql('UPDATE cache SET data=? WHERE key=?', [value, key], insert);
}
this.SQLite.transaction(update);
}
// Copy value to indexedDB
if (this.indexedDB) {
this.indexedDB.objectStore('cache').add({'key': key, 'value': value});
}
return this.cache[key];
}
return false;
});
/**
* Get
*
* @param String key
*
* @return Mixed Returns reference to stored value or false for failure or error
*/
StickyStore.prototype.get = (function(key) {
// Prefix key with store name
key = this.opts.name + this.opts.version + key;
// If cached, return value immediately.
// Data inside webDB is loaded into the store on instantiation,
// so it's available here.
if (this.cache[key]) {
return this.cache[key];
}
// Check localStorage or globalStorage
if (this.storage) {
var value = this.storage.getItem(key);
if (value && value.substr(0, 4) === 'J::O') {
value = JSON.parse(value.substr(4));
}
this.cache[key] = value;
return this.cache[key];
}
// If not, check cookies
else {
var keyEquals = key + "=";
var cookieArray = document.cookie.split(';');
for (var i=0; i<cookieArray.length; i++) {
var cookie = cookieArray[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(keyEquals) === 0) {
this.cache[key] = cookie.substring(keyEquals.length, cookie.length);
return this.cache[key];
}
}
}
// Not found
return false;
});
/**
* Remove
*
* @param String key
*
* @returns Bolean
*/
StickyStore.prototype.remove = (function(key) {
// Prefix key with store name
key = this.opts.name + this.opts.version + key;
// Remove from memory
if (this.cache[key]) {
delete this.cache[key];
}
// Remove cookie
document.cookie = key + '=; expires=-1; domain=' + this.opts.domain + '; path=/';
// Remove localStorage or globalStorage
if (this.storage) {
try {
this.storage.removeItem(key);
}
catch (err) {
console.log('Sticky Error: ' + err);
return false;
}
}
// Remove web SQL
if (this.SQLite) {
// Update if insert fails
this.SQLite.transaction(function(tx) {
tx.executeSql('DELETE FROM cache WHERE key=?', [key]);
});
}
// Remove indexedDB
if (this.indexedDB) {
this.indexedDB.objectStore('cache')['delete'](key);
}
return true;
});
/**
* Remove All
*
* Removes all values in this store from all storage mechanisms
*/
StickyStore.prototype.removeAll = (function() {
var store = this;
for (var key in store.cache) {
store.remove(key);
}
});