Created
November 27, 2020 07:03
-
-
Save tejpochiraju/94b6411f16d5bb93321fd2108f11b51f to your computer and use it in GitHub Desktop.
Example showing how to download large objects from S3 and cache using IndexedDB
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
// Example showing how to download large objects from S3 and cache using IndexedDB | |
// Once downloaded, all future requests for the file are automatically served from IndexedDB. | |
// Offline caching module - | |
import Dexie from 'dexie'; | |
import axios from 'axios'; | |
const db = new Dexie('offline-blobs'); | |
db.version(1).stores({ | |
blobs: 'key,id, blob' | |
}); | |
const downloadAndSaveFile = async (key, id, url) => { | |
const resp = await axios({ | |
url, | |
method: 'GET', | |
responseType: 'blob' // important | |
}); | |
const { data } = resp; | |
await db.blobs.put({ | |
key, | |
id, | |
blob: new Blob([data]) | |
}); | |
}; | |
const getFileUrl = async key => { | |
const data = await db.blobs.get(key); | |
const { blob } = data; | |
return window.URL.createObjectURL(blob); | |
}; | |
// client code - uses React Hooks but should be clear enough | |
const getSensibleUrl = useCallback( | |
async (key, contentId) => { | |
try { | |
const fileUrl = await getFileUrl(key); | |
setSensibleUrl(fileUrl); | |
} catch (error) { | |
// console.log('Err:: ', error); | |
if (error.message === errorMsg) { | |
setMessage('Downloading File...'); | |
const url = await getPreSignedUrl({ s3_key: key }); | |
await downloadAndSaveFile(key, contentId, url); | |
const fileUrl = await getFileUrl(key); | |
setSensibleUrl(fileUrl); | |
} | |
} | |
}, | |
[errorMsg] | |
); | |
useEffect(() => { | |
const { s3_key: key } = content; // content is a prop | |
if (key) { | |
const contentId = id; | |
getSensibleUrl(key, contentId); | |
} | |
}, [content, getSensibleUrl, id]); | |
if (!content.title) { | |
return ( | |
<Grid container alignItems="center" justify="center"> | |
<CircularProgress /> | |
</Grid> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment