cachified-adapter-cloudflare-kv
Version:
Cloudflare KV adapter for @epic-web/cachified
53 lines (52 loc) • 1.53 kB
JavaScript
import { totalTtl } from "@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 = 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);
}
};
}
export {
cloudflareKvCacheAdapter
};
//# sourceMappingURL=index.js.map