UNPKG

@daiso-tech/core

Version:

The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.

110 lines 3.07 kB
/** * @module Cache */ import { TypeCacheError, } from "../../../../cache/contracts/_module-exports.js"; /** * @internal */ export class DatabaseCacheAdapter { adapter; constructor(adapter) { this.adapter = adapter; } async get(key) { const data = await this.adapter.find(key); if (data === null) { return null; } const { expiration, value } = data; if (expiration === null) { return value; } const hasExpired = expiration.getTime() <= new Date().getTime(); if (hasExpired) { await this.adapter.removeExpiredMany([key]); return null; } return value; } async getAndRemove(key) { const value = await this.get(key); if (value !== null) { await this.removeMany([key]); } return value; } async add(key, value, ttl) { try { await this.adapter.insert({ key, value, expiration: ttl?.toEndDate() ?? null, }); return true; } catch { const result = await this.adapter.updateExpired({ expiration: ttl?.toEndDate() ?? null, key, value, }); return result > 0; } } async put(key, value, ttl) { const data = await this.adapter.upsert({ key, value, expiration: ttl?.toEndDate() ?? null, }); if (data === null) { return false; } const { expiration } = data; if (expiration === null) { return true; } const hasExpired = expiration.getTime() <= new Date().getTime(); return !hasExpired; } async update(key, value) { const result = await this.adapter.updateUnexpired({ key, value, }); return result > 0; } async increment(key, value) { try { const result = await this.adapter.incrementUnexpired({ key, value, }); return result > 0; } catch (error) { if (error instanceof TypeCacheError) { throw error; } throw new TypeCacheError(`Unable to increment or decrement none number type key "${key}"`, error); } } async removeAll() { await this.adapter.removeAll(); } async removeMany(keys) { const [promiseResult] = await Promise.allSettled([ this.adapter.removeUnexpiredMany(keys), this.adapter.removeExpiredMany(keys), ]); if (promiseResult.status === "rejected") { throw promiseResult.reason; } const { value: result } = promiseResult; return result > 0; } async removeByKeyPrefix(prefix) { await this.adapter.removeByKeyPrefix(prefix); } } //# sourceMappingURL=database-cache-adapter.js.map