Skip to content

Instantly share code, notes, and snippets.

@chand1012
Created March 5, 2023 14:59
Show Gist options
  • Save chand1012/c177031d40870b233464e2fdc3d13333 to your computer and use it in GitHub Desktop.
Save chand1012/c177031d40870b233464e2fdc3d13333 to your computer and use it in GitHub Desktop.
Use Cloudflare Workers with Deno
const endpoint = (key: string) => {
const accountID = Deno.env.get("WORKERS_KV_ACCOUNT_ID");
const namespaceID = Deno.env.get("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/${Deno.env.get("WORKERS_KV_ACCOUNT_ID")}/storage/kv/namespaces/${Deno.env.get("WORKERS_KV_NAMESPACE_ID")}/bulk`, {
method: "PUT",
headers: {
'X-Auth-Email': Deno.env.get("CLOUDFLARE_EMAIL"),
Authorization: `Bearer ${Deno.env.get("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': Deno.env.get("CLOUDFLARE_EMAIL"),
Authorization: `Bearer ${Deno.env.get("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': Deno.env.get("CLOUDFLARE_EMAIL"),
Authorization: `Bearer ${Deno.env.get("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