@trifrost/core
Version:
Blazingly fast, runtime-agnostic server framework for modern edge and node environments
84 lines (83 loc) • 2.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisRateLimit = exports.RedisCache = exports.RedisStore = exports.RedisStoreAdapter = 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 RedisStoreAdapter {
#redis;
constructor(redis) {
this.#redis = redis;
}
async get(key) {
const val = await this.#redis.get(key);
if (!val)
return null;
return JSON.parse(val);
}
async set(key, value, ttl) {
await this.#redis.set(key, JSON.stringify(value), 'EX', ttl);
}
async del(key) {
await this.#redis.del(key);
}
async delPrefixed(prefix) {
let cursor = '0';
const acc = new Set();
do {
const [next, keys] = await this.#redis.scan(cursor, 'MATCH', prefix + '*', 'COUNT', 250);
cursor = next;
for (let i = 0; i < keys.length; i++)
acc.add(keys[i]);
} while (cursor && cursor !== '0');
if (!acc.size)
return;
for (const batch of (0, array_1.split)([...acc], 100)) {
await this.#redis.del(...batch);
}
}
async stop() {
/* Nothing to do here */
}
}
exports.RedisStoreAdapter = RedisStoreAdapter;
/**
* MARK: Store
*/
class RedisStore extends _Storage_1.Store {
constructor(redis) {
super('RedisStore', new RedisStoreAdapter(redis));
}
}
exports.RedisStore = RedisStore;
/**
* MARK: Cache
*/
class RedisCache extends _Cache_1.TriFrostCache {
constructor(cfg) {
if (!cfg?.store)
throw new Error('RedisCache: Expected a store initializer');
super({
store: new _Storage_1.Store('RedisCache', new RedisStoreAdapter(cfg.store)),
});
}
}
exports.RedisCache = RedisCache;
/**
* MARK: RateLimit
*/
class RedisRateLimit extends _RateLimit_1.TriFrostRateLimit {
constructor(cfg) {
if (!cfg?.store)
throw new Error('RedisRateLimit: Expected a store initializer');
super({
...cfg,
store: new _Storage_1.Store('RedisRateLimit', new RedisStoreAdapter(cfg.store)),
});
}
}
exports.RedisRateLimit = RedisRateLimit;