UNPKG

@trifrost/core

Version:

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

91 lines (90 loc) 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DurableObjectRateLimit = exports.DurableObjectCache = exports.DurableObjectStore = exports.DurableObjectStoreAdapter = void 0; const _Cache_1 = require("../modules/Cache/_Cache"); const _RateLimit_1 = require("../modules/RateLimit/_RateLimit"); const _Storage_1 = require("./_Storage"); /** * MARK: Adapter */ class DurableObjectStoreAdapter { #ns; #id; #path; constructor(ns, path = 'generic') { this.#ns = ns; this.#path = path; this.#id = this.#ns.idFromName(`trifrost-${path}`); } async get(key) { const res = await this.#ns.get(this.#id).fetch(this.keyUrl(key), { method: 'GET' }); if (!res.ok) return null; try { return await res.json(); } catch { return null; } } async set(key, value, ttl) { await this.#ns.get(this.#id).fetch(this.keyUrl(key), { method: 'PUT', body: JSON.stringify({ v: value, ttl }), headers: { 'Content-Type': 'application/json' }, }); } async del(key) { const res = await this.#ns.get(this.#id).fetch(this.keyUrl(key), { method: 'DELETE' }); if (!res?.ok && res?.status !== 404) throw new Error(`TriFrostDurableObjectStore@del: Failed with status ${res.status}`); } async delPrefixed(prefix) { const res = await this.#ns.get(this.#id).fetch(this.keyUrl(prefix + '*'), { method: 'DELETE' }); if (!res?.ok && res?.status !== 404) throw new Error(`TriFrostDurableObjectStore@delPrefixed: Failed with status ${res.status}`); } async stop() { /* Nothing to do here */ } keyUrl(key) { return 'https://do/trifrost-' + this.#path + '?key=' + encodeURIComponent(key); } } exports.DurableObjectStoreAdapter = DurableObjectStoreAdapter; /** * MARK: Store */ class DurableObjectStore extends _Storage_1.Store { constructor(ns, path) { super('DurableObjectStore', new DurableObjectStoreAdapter(ns, path)); } } exports.DurableObjectStore = DurableObjectStore; /** * MARK: Cache */ class DurableObjectCache extends _Cache_1.TriFrostCache { constructor(cfg) { if (!cfg?.store) throw new Error('DurableObjectCache: Expected a store initializer'); super({ store: new _Storage_1.Store('DurableObjectCache', new DurableObjectStoreAdapter(cfg.store, 'cache')), }); } } exports.DurableObjectCache = DurableObjectCache; /** * MARK: RateLimit */ class DurableObjectRateLimit extends _RateLimit_1.TriFrostRateLimit { constructor(cfg) { if (!cfg?.store) throw new Error('DurableObjectRateLimit: Expected a store initializer'); super({ ...cfg, store: new _Storage_1.Store('DurableObjectRateLimit', new DurableObjectStoreAdapter(cfg.store, 'ratelimit')), }); } } exports.DurableObjectRateLimit = DurableObjectRateLimit;