Is it possible to use CloudFlare's Workers KV when developing a Svelte/kit application?
It is possible to build the app then run wrangler dev
when using the CloudFlare Workers adapter:
npm build
wrangler dev
However, I haven't gotten hot module reloading working:
npm dev & wrangler dev
As far as I know, there's no way to emulate Workers KV locally. However, I setup a local Redis instance as a substitute.
Then, I created some wrapper functions for the KV store. In development, it talks to Redis, and in production it talks to Workers KV. For instance, here's the wrapper function for get
.
import { dev } from '$app/env'
import redis from 'redis'
const client = redis.createClient()
const get = promisify(client.get).bind(client)
export const getKvValue = async (key: string): Promise<string | null> => {
return dev ? await get(key) : await KV.get(key)
}
Update: You can actually make things much simpler by just using an object in JavaScript—no need to download and run a Redis binary. Just make sure to JSON.stringify the values before setting them.
import { dev } from '$app/env'
const devKvStore = {}
const devGetKvValue = (key: string) => {
return new Promise((resolve) => {
resolve(devKvStore[key] ?? null)
})
}
const devSetKvValue = (key: string, value: unknown) => {
return new Promise((resolve) => {
devKvStore[key] = JSON.stringify(value)
resolve()
})
}
export const getKvValue = async (key: string): Promise<string | null> => {
return dev ? await devGetKvValue(key) : await KV.get(key)
}
export const setKvValue = async (key: string, value: unknown): Promise<void> => {
return dev ? await devSetKvValue(key, value) : await KV.put(key, value)
}