forked from mrdoob/three.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStorage.js
98 lines (55 loc) · 1.96 KB
/
Storage.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
function Storage() {
const indexedDB = window.indexedDB;
if ( indexedDB === undefined ) {
console.warn( 'Storage: IndexedDB not available.' );
return { init: function () {}, get: function () {}, set: function () {}, clear: function () {} };
}
const name = 'threejs-editor';
const version = 1;
let database;
return {
init: function ( callback ) {
const request = indexedDB.open( name, version );
request.onupgradeneeded = function ( event ) {
const db = event.target.result;
if ( db.objectStoreNames.contains( 'states' ) === false ) {
db.createObjectStore( 'states' );
}
};
request.onsuccess = function ( event ) {
database = event.target.result;
callback();
};
request.onerror = function ( event ) {
console.error( 'IndexedDB', event );
};
},
get: function ( callback ) {
const transaction = database.transaction( [ 'states' ], 'readwrite' );
const objectStore = transaction.objectStore( 'states' );
const request = objectStore.get( 0 );
request.onsuccess = function ( event ) {
callback( event.target.result );
};
},
set: function ( data ) {
const start = performance.now();
const transaction = database.transaction( [ 'states' ], 'readwrite' );
const objectStore = transaction.objectStore( 'states' );
const request = objectStore.put( data, 0 );
request.onsuccess = function () {
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Saved state to IndexedDB. ' + ( performance.now() - start ).toFixed( 2 ) + 'ms' );
};
},
clear: function () {
if ( database === undefined ) return;
const transaction = database.transaction( [ 'states' ], 'readwrite' );
const objectStore = transaction.objectStore( 'states' );
const request = objectStore.clear();
request.onsuccess = function () {
console.log( '[' + /\d\d\:\d\d\:\d\d/.exec( new Date() )[ 0 ] + ']', 'Cleared IndexedDB.' );
};
}
};
}
export { Storage };