UNPKG

mastercache

Version:

Multi-tier cache module for Node.js. Redis, Upstash, CloudfareKV, File, in-memory and others drivers

1 lines 3.68 kB
{"version":3,"sources":["../../../../src/cache/cache-entry/cache-entry.ts","../../../../src/serializers/json.ts"],"sourcesContent":["import { JsonSerializer } from '../../serializers/json';\n\n/**\n * Represents a cache entry stored inside a cache driver.\n */\nexport class CacheEntry {\n /**\n * The key of the cache item.\n */\n #key: string;\n\n /**\n * The value of the item.\n */\n #value: any;\n\n /**\n * The logical expiration is the time in miliseconds when the item\n * will be considered expired. But, if grace period is enabled,\n * the item will still be available for a while.\n */\n #logicalExpiration: number;\n\n #earlyExpiration: number;\n\n static #serializer = new JsonSerializer();\n\n constructor(key: string, item: Record<string, any>) {\n this.#key = key;\n this.#value = item.value;\n this.#logicalExpiration = item.logicalExpiration;\n this.#earlyExpiration = item.earlyExpiration;\n }\n\n getValue() {\n return this.#value;\n }\n\n getKey() {\n return this.#key;\n }\n\n getLogicalExpiration() {\n return this.#logicalExpiration;\n }\n\n getEarlyExpiration() {\n return this.#earlyExpiration;\n }\n\n isLogicallyExpired() {\n return Date.now() >= this.#logicalExpiration;\n }\n\n isEarlyExpired() {\n if (!this.#earlyExpiration) {\n return false;\n }\n\n if (this.isLogicallyExpired()) {\n return false;\n }\n\n return Date.now() >= this.#earlyExpiration;\n }\n\n static fromDriver(key: string, item: string) {\n return new CacheEntry(key, this.#serializer.deserialize(item));\n }\n\n applyFallbackDuration(duration: number) {\n this.#logicalExpiration += duration;\n this.#earlyExpiration = 0;\n return this;\n }\n\n expire() {\n this.#logicalExpiration = Date.now() - 100;\n this.#earlyExpiration = 0;\n return this;\n }\n\n serialize() {\n return CacheEntry.#serializer.serialize({\n value: this.#value,\n logicalExpiration: this.#logicalExpiration,\n earlyExpiration: this.#earlyExpiration,\n });\n }\n}\n","import type { CacheSerializer } from '../types/main';\n\n/**\n * Simple class to serialize and deserialize values using JSON\n */\nexport class JsonSerializer implements CacheSerializer {\n serialize(value: unknown) {\n return J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