UNPKG

@snap/camera-kit

Version:
64 lines 2.52 kB
import { __awaiter } from "tslib"; import { getLogger } from "../logger/logger"; const logger = getLogger("ExpiringPersistence"); export class ExpiringPersistence { constructor(expiration, persistence) { this.expiration = expiration; this.persistence = persistence; this.removeExpired().catch((error) => { logger.warn("Failed to cleanup expired entries on startup.", error); }); } get size() { return this.persistence.size; } retrieve(key) { var _a; return __awaiter(this, void 0, void 0, function* () { const [expiry, value] = (_a = (yield this.persistence.retrieve(key))) !== null && _a !== void 0 ? _a : []; if (value === undefined || expiry === undefined) return undefined; if (Date.now() > expiry) { yield this.persistence.remove(key).catch((error) => { logger.warn(`Key ${key} is expired, but removing it from persistence failed.`, error); }); return undefined; } return value; }); } retrieveAll() { return __awaiter(this, void 0, void 0, function* () { const now = Date.now(); return (yield this.persistence.retrieveAll()).filter(([, [expiry]]) => expiry >= now).map(([, v]) => v); }); } remove(key) { return this.persistence.remove(key); } removeAll() { return __awaiter(this, void 0, void 0, function* () { const results = yield this.persistence.removeAll(); return results.map(([, v]) => v); }); } removeExpired() { return __awaiter(this, void 0, void 0, function* () { for (const [key, [expiry]] of yield this.persistence.retrieveAll()) { if (Date.now() >= expiry) { yield this.persistence .remove(key) .catch((error) => logger.warn(`Failed to remove expired key ${key}.`, error)); } } }); } store(keyOrValue, maybeValue) { const [key, value] = maybeValue === undefined ? [undefined, keyOrValue] : [keyOrValue, maybeValue]; const expiry = Date.now() + this.expiration(value) * 1000; return key === undefined ? this.persistence.store([expiry, value]) : this.persistence.store(key, [expiry, value]); } } //# sourceMappingURL=ExpiringPersistence.js.map