Created
March 5, 2023 14:59
-
-
Save chand1012/c177031d40870b233464e2fdc3d13333 to your computer and use it in GitHub Desktop.
Use Cloudflare Workers with Deno
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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