3 * Copyright 2017 RIFT.IO Inc
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 import appConfiguration
from '../utils/appConfiguration'
20 let versionKeyPrefix
= null;
22 const localCache
= new class {
24 let valueAsString
= localStorage
.getItem(key
);
25 return valueAsString
? JSON
.parse(valueAsString
) : undefined;
28 localStorage
.setItem(key
, typeof val
=== 'string' ? val
: JSON
.stringify(val
));
32 let objCache
= new Map();
34 const storeCache
= new class {
37 objCache
[key
].timerId
&& clearTimeout(objCache
[key
].timerId
)
38 objCache
[key
].timerId
= setTimeout((key
) => delete objCache
[key
], 2000)
39 return objCache
[key
].value
;
41 const obj
= localCache
.get(key
);
45 timerId
: setTimeout((key
) => delete objCache
[key
], 2000)
51 setTimeout(localCache
.set, 100, key
, obj
);
54 timerId
: setTimeout((key
) => delete objCache
[key
], 2000)
58 versionKeyPrefix
= 's-v-' + version
;
59 const currentStoreVersion
= localStorage
.getItem('store-version');
60 if (currentStoreVersion
!== version
) {
62 for (let i
= 0; i
< localStorage
.length
; ++i
) {
63 let key
= localStorage
.key(i
);
64 if (key
.startsWith('s-v-')) {
65 removeItems
.push(key
);
68 removeItems
.forEach((key
) => localStorage
.removeItem(key
));
69 localStorage
.setItem('store-version', version
);
76 this.name
= 's-v-' + name
;
79 return storeCache
.get(this.name
+ key
);
82 storeCache
.set(this.name
+ key
, obj
);
85 return versionKeyPrefix
? Promise
.resolve() : new Promise(
86 (resolve
, reject
) => {
87 appConfiguration
.get().then((config
) => {
88 storeCache
.init(config
.version
);
96 module
.exports
= StoreCache
;