@fedify/fedify
Version:
An ActivityPub server framework
53 lines (52 loc) • 1.5 kB
JavaScript
/**
* A key for a key-value store. An array of one or more strings.
*
* @since 0.5.0
*/
import * as dntShim from "../_dnt.shims.js";
/**
* A key-value store that stores values in memory.
* Do not use this in production as it does not persist values.
*
* @since 0.5.0
*/
export class MemoryKvStore {
#values = {};
#encodeKey(key) {
return JSON.stringify(key);
}
/**
* {@inheritDoc KvStore.get}
*/
get(key) {
const encodedKey = this.#encodeKey(key);
const entry = this.#values[encodedKey];
if (entry == null)
return Promise.resolve(undefined);
const [value, expiration] = entry;
if (expiration != null && dntShim.Temporal.Now.instant().until(expiration).sign < 0) {
delete this.#values[encodedKey];
return Promise.resolve(undefined);
}
return Promise.resolve(value);
}
/**
* {@inheritDoc KvStore.set}
*/
set(key, value, options) {
const encodedKey = this.#encodeKey(key);
const expiration = options?.ttl == null
? null
: dntShim.Temporal.Now.instant().add(options.ttl.round({ largestUnit: "hour" }));
this.#values[encodedKey] = [value, expiration];
return Promise.resolve();
}
/**
* {@inheritDoc KvStore.delete}
*/
delete(key) {
const encodedKey = this.#encodeKey(key);
delete this.#values[encodedKey];
return Promise.resolve();
}
}