1
Fork 0

Add caching of protected images

This commit is contained in:
viktorstrate 2019-08-10 17:00:18 +02:00
parent 0496a65f9c
commit 58b1a07340
2 changed files with 38 additions and 19 deletions

View File

@ -4,6 +4,7 @@ import { Loader } from 'semantic-ui-react'
import { Photo } from './Photo'
import PresentView from './PresentView'
import PropTypes from 'prop-types'
import { fetchProtectedImage } from './ProtectedImage'
const Gallery = styled.div`
display: flex;
@ -55,9 +56,9 @@ class PhotoGallery extends React.Component {
}
preloadImages() {
function preloadImage(url) {
async function preloadImage(url) {
var img = new Image()
img.src = url
img.src = await fetchProtectedImage(url)
}
const { activeIndex = -1, photos } = this.props

View File

@ -1,5 +1,34 @@
import React, { useState, useEffect } from 'react'
let imageCache = {}
export async function fetchProtectedImage(src) {
if (src) {
if (imageCache[src]) {
console.log('Found image from cache', src)
return imageCache[src]
}
let image = await fetch(src, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
})
image = await image.blob()
const url = URL.createObjectURL(image)
console.log(
`Saved image to cache, ${src}. New cache size: ${
Object.keys(imageCache).length
}`
)
imageCache[src] = url
return url
}
}
/**
* An image that needs a authorization header to load
*/
@ -20,28 +49,17 @@ class ProtectedImage extends React.Component {
return true
}
async fetchImage() {
if (this.props.src && this.shouldRefresh) {
render() {
if (this.shouldRefresh) {
this.shouldRefresh = false
let image = await fetch(this.props.src, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
})
image = await image.blob()
const url = URL.createObjectURL(image)
this.setState({
imgSrc: url,
loadedSrc: this.props.src,
fetchProtectedImage(this.props.src).then(imgSrc => {
this.setState({
imgSrc,
})
})
}
}
render() {
this.fetchImage()
return <img {...this.props} src={this.state.imgSrc} />
}
}