Created
March 6, 2023 06:59
-
-
Save rstacruz/e5128b8ae10dcd069771248ba1368367 to your computer and use it in GitHub Desktop.
Using miniflare for Cloudflare Worker KV in Astro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getRuntime } from "@astrojs/cloudflare/runtime"; | |
import type { KVNamespace } from "@cloudflare/workers-types"; | |
/** The KV key (eg, env["KV"]) */ | |
const KV_KEY = "KV" as const; | |
/** | |
* Returns a Cloudflare Worker KV store. | |
* In dev, it returns a mock one based on Miniflare. | |
*/ | |
export async function getKV(request: Request): Promise<KVNamespace> { | |
if (import.meta.env.DEV) return getMockKV(); | |
const kv = getRuntimeKV(request); | |
if (kv) return kv; | |
throw "No KV provider available"; | |
} | |
type Env = { | |
[key in typeof KV_KEY]: KVNamespace; | |
} | |
export async function getRuntimeKV(request: Request): Promise<KVNamespace> { | |
const runtime = getRuntime<Env>(request); | |
// runtime: { env: { KV: KVNamespace {}, ASSETS: Fetcher {} }, name: 'cloudflare' } | |
const kv = runtime?.env[KV_KEY]; | |
return kv; | |
} | |
export async function getMockKV(): Promise<KVNamespace> { | |
(global as any).miniflare ??= await (async () => { | |
const { Miniflare } = await import("miniflare"); | |
return new Miniflare({ | |
kvNamespaces: [KV_KEY], | |
script: '', | |
}); | |
})(); | |
return (global as any).miniflare.getKVNamespace(KV_KEY); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example: using miniflare for Cloudflare Worker KV in Astro | |
// | |
// Running astro in development mode (`astro dev`) won't allow you to | |
// use Cloudflare features like KV. To get around this, we can use | |
// `miniflare`. | |
import { getKV } from "./get_kv"; | |
// instead of using `getRuntime(request).env.KV` to get the KV instance, | |
// use this: | |
const kv = getKV(); | |
kv.put("hello", "world"); | |
kv.delete("hello"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment