UNPKG

@trifrost/core

Version:

Blazingly fast, runtime-agnostic server framework for modern edge and node environments

86 lines (85 loc) 2.47 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.KVRateLimit = exports.KVCache = exports.KVStore = exports.KVStoreAdapter = void 0; const array_1 = require("@valkyriestudios/utils/array"); const _Cache_1 = require("../modules/Cache/_Cache"); const _RateLimit_1 = require("../modules/RateLimit/_RateLimit"); const _Storage_1 = require("./_Storage"); /** * MARK: Adapter */ class KVStoreAdapter { #kv; constructor(kv) { this.#kv = kv; } async get(key) { return this.#kv.get(key, 'json'); } async set(key, value, ttl) { await this.#kv.put(key, JSON.stringify(value), { expirationTtl: ttl }); } async del(key) { await this.#kv.delete(key); } async delPrefixed(prefix) { let cursor; const acc = new Set(); do { const list = await this.#kv.list({ prefix, cursor }); cursor = list.cursor || undefined; for (let i = 0; i < list.keys.length; i++) { acc.add(list.keys[i].name); } } while (cursor); if (!acc.size) return; for (const batch of (0, array_1.split)([...acc], 10)) { const proms = []; /* Sadly KV namespace currently does not support direct bulk deletion */ for (let i = 0; i < batch.length; i++) proms.push(this.#kv.delete(batch[i])); await Promise.all(proms); } } async stop() { /* Nothing to do here */ } } exports.KVStoreAdapter = KVStoreAdapter; /** * MARK: Store */ class KVStore extends _Storage_1.Store { constructor(kv) { super('KVStore', new KVStoreAdapter(kv)); } } exports.KVStore = KVStore; /** * MARK: Cache */ class KVCache extends _Cache_1.TriFrostCache { constructor(cfg) { if (!cfg?.store) throw new Error('KVCache: Expected a store initializer'); super({ store: new _Storage_1.Store('KVCache', new KVStoreAdapter(cfg.store)), }); } } exports.KVCache = KVCache; /** * MARK: RateLimit */ class KVRateLimit extends _RateLimit_1.TriFrostRateLimit { constructor(cfg) { if (!cfg?.store) throw new Error('KVRateLimit: Expected a store initializer'); super({ ...cfg, store: new _Storage_1.Store('KVRateLimit', new KVStoreAdapter(cfg.store)), }); } } exports.KVRateLimit = KVRateLimit;