const baseUrl = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT}/storage/kv/namespaces/${CLOUDFLARE_NAMESPACE}`;
const headers = { ... }; // Auth stuff
class CloudflareRest {
EXPIRES = true;
async get(key) {
const res = await fetch(`${baseUrl}/values/${key}`, { headers });
if (res.status === 404) return null; // It does not exist
const data = await (res.headers.get("content-type").includes("json")
? res.json()
: res.text());
if (typeof data !== "string") return null;
return JSON.parse(data);
}
async set(key, body, { expires }) {
const expiration = expires ? `expiration_ttl=${expires}&` : "";
await fetch(`${baseUrl}/values/${key}?${expiration}`, {
method: "PUT",
headers,
body: JSON.stringify(body),
});
return key;
}
async keys(prefix) {
const res = await fetch(`${baseUrl}/keys`, { headers });
const data = await res.json();
return data.result
.map((it) => it.name)
.filter((key) => key.startsWith(prefix));
}
async *iterate(prefix) {
// ...
}
}
const store = kv(CloudflareRest);
// console.log(await store.get("hello"));
// console.log(await store.set("hello", { world: "spins" }));
// console.log(await store.get("hello"));
const baseUrl = `https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT}/storage/kv/namespaces/${CLOUDFLARE_NAMESPACE}`;
const headers = { ... }; // Auth stuff
class CloudflareRest {
EXPIRES = true;
async get(key) {
const res = await fetch(`${baseUrl}/values/${key}`, { headers });
if (res.status === 404) return null; // It does not exist
const data = await (res.headers.get("content-type").includes("json")
? res.json()
: res.text());
if (typeof data !== "string") return null;
return JSON.parse(data);
}
async set(key, body, { expires }) {
const expiration = expires ? `expiration_ttl=${expires}&` : "";
await fetch(`${baseUrl}/values/${key}?${expiration}`, {
method: "PUT",
headers,
body: JSON.stringify(body),
});
return key;
}
async keys(prefix) {
const res = await fetch(`${baseUrl}/keys`, { headers });
const data = await res.json();
return data.result
.map((it) => it.name)
.filter((key) => key.startsWith(prefix));
}
async *iterate(prefix) {
// ...
}
}
const store = kv(CloudflareRest);
// console.log(await store.get("hello"));
// console.log(await store.set("hello", { world: "spins" }));
// console.log(await store.get("hello"));