@trifrost/core
Version:
Blazingly fast, runtime-agnostic server framework for modern edge and node environments
84 lines (83 loc) • 2.6 kB
JavaScript
import { TriFrostCache } from '../modules/Cache/_Cache';
import { TriFrostRateLimit } from '../modules/RateLimit/_RateLimit';
import { Store } from './_Storage';
/**
* MARK: Adapter
*/
export 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);
}
}
/**
* MARK: Store
*/
export class DurableObjectStore extends Store {
constructor(ns, path) {
super('DurableObjectStore', new DurableObjectStoreAdapter(ns, path));
}
}
/**
* MARK: Cache
*/
export class DurableObjectCache extends TriFrostCache {
constructor(cfg) {
if (!cfg?.store)
throw new Error('DurableObjectCache: Expected a store initializer');
super({
store: new Store('DurableObjectCache', new DurableObjectStoreAdapter(cfg.store, 'cache')),
});
}
}
/**
* MARK: RateLimit
*/
export class DurableObjectRateLimit extends TriFrostRateLimit {
constructor(cfg) {
if (!cfg?.store)
throw new Error('DurableObjectRateLimit: Expected a store initializer');
super({
...cfg,
store: new Store('DurableObjectRateLimit', new DurableObjectStoreAdapter(cfg.store, 'ratelimit')),
});
}
}