Skip to content

Instantly share code, notes, and snippets.

@velotiotech
Created June 25, 2020 10:08
Show Gist options
  • Save velotiotech/5d940494c4e84d422597b25b43418646 to your computer and use it in GitHub Desktop.
Save velotiotech/5d940494c4e84d422597b25b43418646 to your computer and use it in GitHub Desktop.
Country request count app logic
const fetch = require('node-fetch')
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
const country = request.cf.country
const url = `https://api.cloudflare.com/client/v4/accounts/account-id/storage/kv/namespaces/namespace-id/values/${country}`
let count = await requests.get(country)
if (!count) {
count = 1
} else {
count = parseInt(count) + 1
}
try {
response = await fetch(url, {
method: 'PUT',
headers: {"X-Auth-Email": "email", "X-Auth-Key": "auth-key"},
body: `${count}`
})
} catch (error) {
return new Response(error, { status: 500 })
}
return new Response(`${country}: ${count}`, { status: 200 })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment