Skip to content

Instantly share code, notes, and snippets.

@chand1012
Created March 5, 2023 14:37
Show Gist options
  • Save chand1012/4bf658e8cd79cb80dd4ea6d17a1b5648 to your computer and use it in GitHub Desktop.
Save chand1012/4bf658e8cd79cb80dd4ea6d17a1b5648 to your computer and use it in GitHub Desktop.
Use cloudflare workers anywhere you can use Fetch
// info https://giuseppegurgone.com/vercel-cloudflare-kv
// api docs https://developers.cloudflare.com/api/operations/workers-kv-namespace-write-multiple-key-value-pairs
const endpoint = (key: string) => {
const accountID = process.env.WORKERS_KV_ACCOUNT_ID;
const namespaceID = process.env.WORKERS_KV_NAMESPACE_ID;
return `https://api.cloudflare.com/client/v4/accounts/${accountID}/storage/kv/namespaces/${namespaceID}/values/${key}`
};
export const set = async (key: string, value: string, ttl: number = 0, expiration: number = 0) => {
const { success, result, errors } = await fetch(`https://api.cloudflare.com/client/v4/accounts/${process.env.WORKERS_KV_ACCOUNT_ID}/storage/kv/namespaces/${process.env.WORKERS_KV_NAMESPACE_ID}/bulk`, {
method: "PUT",
headers: {
'X-Auth-Email': process.env.CLOUDFLARE_EMAIL as string,
Authorization: `Bearer ${process.env.CLOUDFLARE_KV_API_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify([{key, value, expiration_ttl: ttl, expiration}]),
}).then(response => response.json());
if (!success) {
throw new Error(errors?.join(", ") || "Unknown error");
}
return result;
};
export const get = async (key: string) => {
const result = await fetch(endpoint(key), {
method: "GET",
headers: {
'X-Auth-Email': process.env.CLOUDFLARE_EMAIL as string,
Authorization: `Bearer ${process.env.CLOUDFLARE_KV_API_TOKEN}`,
"Content-Type": "application/json",
}
}).then(response => response.text());
const parsedJSON = JSON.parse(result);
if (parsedJSON?.errors?.length > 0) {
return null;
}
return result;
};
export const del = async (key: string) => {
const { success, result, errors } = await fetch(endpoint(key), {
method: "DELETE",
headers: {
'X-Auth-Email': process.env.CLOUDFLARE_EMAIL as string,
Authorization: `Bearer ${process.env.CLOUDFLARE_KV_API_TOKEN}`,
"Content-Type": "application/json",
}
}).then(response => response.json());
if (!success) {
throw new Error(errors?.join(", ") || "Unknown error");
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment