Created
June 25, 2020 10:08
-
-
Save velotiotech/5d940494c4e84d422597b25b43418646 to your computer and use it in GitHub Desktop.
Country request count app logic
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 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