-
Notifications
You must be signed in to change notification settings - Fork 0
/
remoteFileCache.js
71 lines (64 loc) · 2.47 KB
/
remoteFileCache.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
import * as FileSystem from 'expo-file-system'
export const CACHE_FOLDER = `${FileSystem.cacheDirectory}`
export default class FileCacheManager {
static async getOrCache(uri, key, changedTimestamp = undefined) {
const fileLocation = FileCacheManager.getCacheKey(key);
const fileInfo = await FileSystem.getInfoAsync(fileLocation);
if (fileInfo.exists) {
if (changedTimestamp && changedTimestamp > fileInfo.modificationTime) {
try {
await FileCacheManager.updateCachedFile(uri, fileLocation);
} catch (ex) {
return Promise.reject('Error while caching remote file');
}
}
return FileCacheManager.getContentAsString(key);
} else {
try {
await FileCacheManager.updateCachedFile(uri, fileLocation);
} catch (ex) {
return Promise.reject('Error while caching remote file');
}
return FileCacheManager.getContentAsString(key);
}
}
static async getLastModifiedTimeStamp(key) {
const fileLocation = FileCacheManager.getCacheKey(key);
const fileInfo = await FileSystem.getInfoAsync(fileLocation);
if (fileInfo.exists) {
return fileInfo.modificationTime;
}
return Promise.reject('No file for the given key exists');
}
static async updateCachedFile(uri, fileLocation) {
const resumableDownload = await FileSystem.createDownloadResumable(uri, fileLocation, {});
try {
const response = await resumableDownload.downloadAsync();
if (response && response.status !== 200) {
resumableDownload.pauseAsync();
FileSystem.deleteAsync(fileLocation, {idempotent: true});
}
} catch (error) {
console.log(error);
}
}
static async get(key) {
const fileLocation = FileCacheManager.getCacheKey(key);
try {
return await FileSystem.getContentUriAsync(fileLocation);
} catch (ex) {
return Promise.reject(ex);
}
}
static async getContentAsString(key) {
const fileLocation = FileCacheManager.getCacheKey(key);
try {
return await FileSystem.readAsStringAsync(fileLocation);
} catch (ex) {
return Promise.reject(ex);
}
}
static getCacheKey(key) {
return `${CACHE_FOLDER}${key}`;
}
}