@nuxthub/core
Version:
Build full-stack Nuxt applications on Cloudflare, with zero configuration.
54 lines (53 loc) • 1.28 kB
JavaScript
import { ofetch } from "ofetch";
import { joinURL } from "ufo";
import { createError } from "h3";
import { requireNuxtHubFeature } from "../../../utils/features.js";
export function hubCacheBinding(name = "CACHE") {
const binding = process.env[name] || globalThis.__env__?.[name] || globalThis[name];
if (!binding) {
throw createError(`Missing Cloudflare KV binding (${name})`);
}
return binding;
}
export function proxyHubCache(projectUrl, secretKey, headers) {
requireNuxtHubFeature("cache");
const cacheAPI = ofetch.create({
baseURL: joinURL(projectUrl, "/api/_hub/cache"),
headers: {
Authorization: `Bearer ${secretKey}`,
...headers
}
});
const cache = {
async list() {
return cacheAPI("/", {
method: "GET"
});
},
async get(key) {
return cacheAPI(`/${key}`, {
method: "GET"
});
},
async del(key) {
await cacheAPI(`/${key}`, {
method: "DELETE"
});
return;
},
async clear(base) {
await cacheAPI(`/clear/${base}`, {
method: "DELETE"
});
return;
},
async batchDel(keys) {
await cacheAPI("/batch-delete", {
method: "POST",
body: { keys }
});
return;
}
};
return cache;
}