Created
March 5, 2023 14:37
-
-
Save chand1012/4bf658e8cd79cb80dd4ea6d17a1b5648 to your computer and use it in GitHub Desktop.
Use cloudflare workers anywhere you can use Fetch
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
// 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