UNPKG

cachified-adapter-cloudflare-kv

Version:
53 lines (52 loc) 1.65 kB
"use strict"; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const cachified = require("@epic-web/cachified"); function buildCacheKey(givenKey, keyPrefix) { return keyPrefix ? `${keyPrefix}:${givenKey}` : givenKey; } async function deleteOperation(kv, key, keyPrefix) { const cacheKey = buildCacheKey(key, keyPrefix); await kv.delete(cacheKey); } async function getOperation(kv, key, keyPrefix) { const cacheKey = buildCacheKey(key, keyPrefix); const { value, metadata } = await kv.getWithMetadata(cacheKey, { type: "text" }); if (value === null) { return value; } const jsonValue = JSON.parse(value); return { value: jsonValue, metadata }; } async function setOperation(kv, key, value, keyPrefix) { const cacheKey = buildCacheKey(key, keyPrefix); let expirationTtl = cachified.totalTtl(value.metadata); if (expirationTtl === Infinity) { expirationTtl = void 0; } else { expirationTtl = Math.max(Math.ceil(expirationTtl / 1e3), 60); } await kv.put(cacheKey, JSON.stringify(value.value), { expirationTtl, metadata: value.metadata }); return value.value; } function cloudflareKvCacheAdapter(config) { return { name: config.name ?? "CloudflareKV", get: async (key) => { return getOperation(config.kv, key, config.keyPrefix); }, set: async (key, value) => { return await setOperation(config.kv, key, value, config.keyPrefix); }, delete: async (key) => { await deleteOperation(config.kv, key, config.keyPrefix); } }; } exports.cloudflareKvCacheAdapter = cloudflareKvCacheAdapter; //# sourceMappingURL=index.cjs.map