UNPKG

@trifrost/core

Version:

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

78 lines (77 loc) 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Store = void 0; const number_1 = require("@valkyriestudios/utils/number"); const string_1 = require("@valkyriestudios/utils/string"); class Store { #name; adapter; #ctx = null; constructor(name, adapter, ctx) { this.#name = name; this.adapter = adapter; if (ctx) this.#ctx = ctx; } get name() { return this.#name; } async get(key) { if (!(0, string_1.isNeString)(key)) throw new Error(this.#name + '@get: Invalid key'); try { const val = await this.adapter.get(key); return Object.prototype.toString.call(val) === '[object Object]' || Array.isArray(val) ? val : null; } catch (err) { this.#ctx?.logger?.error?.(err, { key }); return null; } } async set(key, value, opts) { if (!(0, string_1.isNeString)(key)) throw new Error(this.#name + '@set: Invalid key'); if (Object.prototype.toString.call(value) !== '[object Object]' && !Array.isArray(value)) throw new Error(this.#name + '@set: Invalid value'); const TTL = (0, number_1.isIntGt)(opts?.ttl, 0) ? opts.ttl : 60; try { await this.adapter.set(key, value, TTL); } catch (err) { this.#ctx?.logger?.error?.(err, { key, value, opts }); } } async del(val) { if ((0, string_1.isNeString)(val)) { try { await this.adapter.del(val); } catch (err) { this.#ctx?.logger?.error?.(err, { val }); } } else if ((0, string_1.isNeString)(val?.prefix)) { try { await this.adapter.delPrefixed(val.prefix); } catch (err) { this.#ctx?.logger?.error?.(err, { val }); } } else { throw new Error(this.#name + '@del: Invalid deletion value'); } } async stop() { try { await this.adapter.stop(); } catch (err) { this.#ctx?.logger?.error?.(err); } } spawn(ctx) { return new Store(this.name, this.adapter, ctx); } } exports.Store = Store;