Created
March 21, 2019 18:05
-
-
Save schabluk/1e553b5f15db87cbd9ec9df32ea77807 to your computer and use it in GitHub Desktop.
Estimate Browser Storage capacity
This file contains hidden or 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
import { types } from 'mobx-state-tree' | |
import bytes from 'bytes' | |
/* | |
* See: https://developers.google.com/web/updates/2016/06/persistent-storage | |
* See: https://developers.google.com/web/updates/2017/08/estimating-available-storage-space | |
*/ | |
const StorageEstimate = types | |
.model('StorageEstimate', { | |
usage: types.maybe(types.number), | |
quota: types.maybe(types.number), | |
}) | |
.views(self => ({ | |
get usageMB() { | |
return bytes(self.usage, { unit: 'mb' }) | |
}, | |
get quotaMB() { | |
return bytes(self.quota, { unit: 'mb' }) | |
}, | |
})) | |
.actions(self => { | |
return { | |
afterCreate() { | |
const { storage } = navigator | |
if ('storage' in navigator && 'estimate' in storage) { | |
storage.estimate().then(({ usage, quota }) => self.update(usage, quota)) | |
} else { | |
throw new Error(`Cannot estimate available storage space.`) | |
} | |
}, | |
update(usage, quota) { | |
self.usage = usage | |
self.quota = quota | |
}, | |
} | |
}) | |
export default StorageEstimate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment