Files
splatoon3.ink/app/common/ValueCache.mjs
Matt Isenhower 45f50c917b
Some checks are pending
Build frontend / build (24.x) (push) Waiting to run
Lint / lint (push) Waiting to run
Tests / test (24.x) (push) Waiting to run
Don't repost when the last post time can't be read
During an R2 outage, failed reads of the last post time looked like
"never posted", so every account posted again. Read it strictly and skip
an account whose time can't be read. Retry saving the time after a post,
and record a post that went out separately from a failed save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:16:29 -08:00

69 lines
1.6 KiB
JavaScript

import { storage } from './storage/index.mjs';
/** A small JSON value with an optional expiry, kept in private storage under cache/. */
export default class ValueCache
{
constructor(key) {
this._key = key;
}
get path() {
return `cache/${this._key}.json`;
}
/**
* @param {{ strict?: boolean }} [options] strict: throw when the value cannot be read, instead
* of answering null as if nothing were cached
* @returns {Promise<object|null>} The stored item
*/
async _getRawItem({ strict = false } = {}) {
try {
return await storage().private.readJson(this.path);
} catch (e) {
if (strict) {
throw e;
}
return null;
}
}
/**
* @param {{ strict?: boolean }} [options]
* @returns {Promise<object|null>} The stored item, or null if missing or expired
*/
async get(options) {
let item = await this._getRawItem(options);
// If the cached value is already expired, return null
if (item && item.expires && new Date(item.expires) < new Date) {
return null;
}
return item;
}
/**
* @param {{ strict?: boolean }} [options]
* @returns {Promise<unknown>} The stored value, or null if missing or expired
*/
async getData(options) {
let item = await this.get(options);
return item && item.data;
}
async getCachedAt() {
let item = await this._getRawItem();
return (item && item.cachedAt) ? new Date(item.cachedAt) : null;
}
async setData(data, expires = null) {
let cachedAt = new Date;
let serialized = JSON.stringify({ expires, data, cachedAt }, undefined, 2);
await storage().private.writeText(this.path, serialized);
}
}