UNPKG

@nuxthub/core

Version:

Build full-stack Nuxt applications on Cloudflare, with zero configuration.

45 lines (44 loc) 1.41 kB
import { createStorage } from "unstorage"; import httpDriver from "unstorage/drivers/http"; import cloudflareKVBindingDriver from "unstorage/drivers/cloudflare-kv-binding"; import { joinURL } from "ufo"; import { createError } from "h3"; import { requireNuxtHubFeature } from "../../../utils/features.js"; import { getCloudflareAccessHeaders } from "../../../utils/cloudflareAccess.js"; import { useRuntimeConfig } from "#imports"; let _kv; export function hubKV() { requireNuxtHubFeature("kv"); if (_kv) { return _kv; } const hub = useRuntimeConfig().hub; const binding = process.env.KV || globalThis.__env__?.KV || globalThis.KV; if (hub.remote && hub.projectUrl && !binding) { const cfAccessHeaders = getCloudflareAccessHeaders(hub.cloudflareAccess); _kv = proxyHubKV(hub.projectUrl, hub.projectSecretKey || hub.userToken, cfAccessHeaders); return _kv; } if (binding) { _kv = createStorage({ driver: cloudflareKVBindingDriver({ binding }) }); return _kv; } throw createError("Missing Cloudflare KV binding (KV)"); } export function proxyHubKV(projectUrl, secretKey, headers) { requireNuxtHubFeature("kv"); const storage = createStorage({ driver: httpDriver({ base: joinURL(projectUrl, "/api/_hub/kv/"), headers: { Authorization: `Bearer ${secretKey}`, ...headers } }) }); return storage; }