API
// kv.ts
import Cloudflare from 'cloudflare';
const client = new Cloudflare({
apiToken: process.env.CLOUDFLARE_KV_TOKEN as string
});
const account_id = process.env.CLOUDFLARE_ACCOUNT_ID as string;
const namespace_id = process.env.CLOUDFLARE_KV_ID as string;
export async function getValue(key: string) {
const res = await client.kv.namespaces.values.get(key, {
account_id,
namespace_id
}).asResponse();
if (res.status === 404) {
return null;
}
if (res.ok === false) {
throw new Error(`读取键值失败:${res.status}`);
}
return await res.text();
}
export async function setValue(key: string, value: string) {
await client.kv.namespaces.values.update(key, {
account_id,
namespace_id,
value
});
}