Created
January 2, 2019 18:17
-
-
Save janicduplessis/35b080e3982e829050c635783552e803 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const DISK_CACHE_ENABLED = true; | |
const ONE_DAY = 24 * 60 * 60 * 1000; | |
const MAX_STORE_SIZE = 1 * 1024 * 1024; // 1mb, TODO: figure out how big this can be. | |
const RELAY_STORE_KEY = 'relay_store'; | |
const RELAY_STORE_META_KEY = 'relay_store_meta'; | |
const DEFAULT_META = { | |
lastGC: Date.now(), | |
environment: getConfig().environment, | |
appVersion: Device.version(), | |
}; | |
let _relayEnvironment; | |
let _relayStoreMeta = DEFAULT_META; | |
export async function initialize() { | |
try { | |
if (!DISK_CACHE_ENABLED) { | |
_relayEnvironment = createRelayEnvironment(); | |
return; | |
} | |
// For now we will be conservative with the offline cache and purge it after | |
// one day. | |
const storeMetaJSON = await AsyncStorage.getItem(RELAY_STORE_META_KEY); | |
_relayStoreMeta = storeMetaJSON ? JSON.parse(storeMetaJSON) : DEFAULT_META; | |
if ( | |
Date.now() - _relayStoreMeta.lastGC > ONE_DAY || | |
_relayStoreMeta.appVersion !== Device.version() || | |
_relayStoreMeta.environment !== getConfig().environment | |
) { | |
doStoreGC(); | |
_relayEnvironment = createRelayEnvironment(); | |
} else { | |
const serializedData = await AsyncStorage.getItem(RELAY_STORE_KEY); | |
_relayEnvironment = createRelayEnvironment( | |
serializedData ? JSON.parse(serializedData) : null, | |
); | |
} | |
} catch (err) { | |
Log.error(err); | |
_relayEnvironment = createRelayEnvironment(); | |
} | |
} | |
async function saveStore() { | |
if (!_relayEnvironment || !DISK_CACHE_ENABLED) { | |
return; | |
} | |
const seralizedData = JSON.stringify( | |
_relayEnvironment.getStore().getSource(), | |
); | |
if (seralizedData.length > MAX_STORE_SIZE) { | |
doStoreGC(); | |
} else { | |
AsyncStorage.setItem(RELAY_STORE_KEY, seralizedData); | |
updateStoreMeta({ | |
environment: getConfig().environment, | |
appVersion: Device.version(), | |
}); | |
} | |
} | |
function updateStoreMeta(data) { | |
_relayStoreMeta = { | |
..._relayStoreMeta, | |
...data, | |
}; | |
AsyncStorage.setItem(RELAY_STORE_META_KEY, JSON.stringify(_relayStoreMeta)); | |
} | |
function doStoreGC() { | |
if (_relayEnvironment) { | |
_relayEnvironment.getStore()._scheduleGC(); | |
} | |
if (DISK_CACHE_ENABLED) { | |
AsyncStorage.removeItem(RELAY_STORE_KEY); | |
updateStoreMeta({ lastGC: Date.now() }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment