@lightspeedgraphics/asset-cache
v0.1.14
Published
asset-cache is a indexeddb persistence layer for caching large assets. It provides a simple interface to fetch() remote assets which are automatically persisted for subsequent requests.
Downloads
32
Readme
asset-cache
A cache for persisting large assets.
npm install @lightspeedgraphics/asset-cache --save
overview
asset-cache is a configurable persistence layer for caching large assets. It provides a simple interface to fetch()
remote assets which are then persisted and returned for subsequent requests. Internally the asset-cache operates over a user defined persistence layer which may (or may not) persist assets.
Additionally, the asset-cache provides a Quota
api which allows callers to inspect the storage limits of the end users browser. (note: this api is dependent on the navigator.storage
api being available.)
usage
The following is the general usage for the api. The asset cache requires the caller to pass a provider type on the asset cache constructor. This library provides two built-in providers IDBProvider
and NullProvider
. The code below uses the IDBProvider
to provide the asset cache with 1GB storage.
import { AssetCache, IDBProvider } from "asset-cache"
// create a idb backed asset-cache.
const cache = new AssetCache( new IDBProvider({ size: 1073741824 }) )
const blob_0 = await cache.fetch("http://domain.com/resource.dat") // slow
const blob_1 = await cache.fetch("http://domain.com/resource.dat") // fast
// clear the cache
await cache.clear()
quotas
One thing to be mindful of when leveraging this library is knowing the storage limits on the end users browser. This library
provides a Quota
api which should be queried prior to initializing the cache. The following implementation requests a
storage quota and creates a IDBProvider
only if the estimation is greater than or equal to the space required
. If
the quota is less than the space required, just default to a NullProvider
which acts as a pass-through.
import { AssetCache, IDBProvider, NullProvider, Quota } from "asset-cache"
// the following code returns a asset-cache implementation
// based on the results obtained from a quota estimation.
// for a estimation of 0, we return a pass through (null),
// provider, otherwise we return a IDBProvider with the
// required size set.
const required = 536870912 // 512mb
const getCache = () => Quota.estimate()
.then(estimate => (estimate.quota >= required)
? new AssetCache(new IDBProvider({ size: required }))
: new AssetCache(new NullProvider()))
getting started
This project comes with a example project (see ./example directory) that can be run with yarn example
. This will boot a small web application on port 5000
in watch mode.
Other available commands are:
yarn install # installs local dev dependencies.
yarn test # runs browser tests, writes coverage.
yarn example # small example scripting tests (served on port 5000)
yarn build # builds a redistributable npm package.