shelving
Version:
Toolkit for using data in JavaScript.
45 lines (44 loc) • 2.05 kB
JavaScript
import { AVOID_REFRESH } from "../../store/FetchStore.js";
import { awaitDispose } from "../../util/dispose.js";
import { APICache } from "../cache/APICache.js";
import { ThroughAPIProvider } from "./ThroughAPIProvider.js";
/**
* API provider wrapper that serves requests through an `APICache`.
* - Constructor accepts a `source` provider and an optional default `maxAge`.
* - On `call(...)`, triggers `cache.refresh(maxAge)` for the endpoint+payload before awaiting `cache.call(...)`.
* - `invalidate`, `invalidateAll`, `refresh`, and `refreshAll` pass through to the underlying cache and use `this.maxAge` as the default refresh timing.
*
* @param `maxAge` The maximum age used when calling `call()` (defaults to `AVOID_REFRESH`, i.e. only refresh if the value is invalidated or still loading).
* - Note: This is not used for `refresh()` calls — when you call `refresh()` you likely mean "do it now".
* - When we are using `call()` on a cache, the entire point of the cache is to "cache", so the default isn't `0` like it is for `refresh()`
*/
export class CachedAPIProvider extends ThroughAPIProvider {
maxAge;
_cache;
constructor(source, maxAge = AVOID_REFRESH) {
super(source);
this.maxAge = maxAge;
this._cache = new APICache(source);
}
// Override call to use the cache racther than calling fresh each time.
call(endpoint, payload, _options, caller = this.call) {
return this._cache.call(endpoint, payload, this.maxAge, caller);
}
invalidate(endpoint, payload) {
this._cache.invalidate(endpoint, payload);
}
invalidateAll(endpoint) {
this._cache.invalidateAll(endpoint);
}
refresh(endpoint, payload) {
this._cache.refresh(endpoint, payload, this.maxAge);
}
refreshAll(endpoint) {
this._cache.refreshAll(endpoint, this.maxAge);
}
// Implement `AsyncDisposable`
async [Symbol.asyncDispose]() {
await awaitDispose(this._cache, // Dispose the cache.
super[Symbol.asyncDispose]());
}
}