Skip to content

Instantly share code, notes, and snippets.

@brockbnntt
Forked from muan/worker.js
Last active July 2, 2025 13:01
Show Gist options
  • Select an option

  • Save brockbnntt/9f7f6df7936c602a2a63b947e1e1090b to your computer and use it in GitHub Desktop.

Select an option

Save brockbnntt/9f7f6df7936c602a2a63b947e1e1090b to your computer and use it in GitHub Desktop.
export default {
async fetch(request, env) {
if (request.method !== 'POST' && request.method !== 'GET') {
return
}
else if (request.method == 'POST') {
const url = new URL(request.url)
const id = url.searchParams.get('id')
const emoji = ensureEmoji(await request.text())
if (!id || !emoji) return new Response('not ok', {status: 500})
const key = `${id}:${emoji}`
// https://developers.cloudflare.com/workers/runtime-apis/kv/
const currentCount = Number(await(env.NAMESPACE.get(key)) || 0)
await env.NAMESPACE.put(key, currentCount + 1)
return new Response('ok')
}
else if (request.method == 'GET') {
const url = new URL(request.url)
const id = url.searchParams.get('id')
const prefix = id + ":"
const listResult = await env.NAMESPACE.list({ prefix: prefix })
const keys = (listResult.keys || 0)
const values = {}
for (var key in keys) {
const name = keys[key]["name"]
const emoji = name.slice(prefix.length);
const count = await env.NAMESPACE.get(name)
values[emoji] = parseInt(count)
}
return Response.json(values, {
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "https://YOURWEBSITE.COM",
"Access-Control-Allow-Methods": "GET"
}
})
}
}
}
function ensureEmoji(emoji) {
const segments = Array.from(new Intl.Segmenter({ granularity: 'character' }).segment(emoji.trim()))
const parsedEmoji = segments.length > 0 ? segments[0].segment : null
if (/\p{Emoji}/u.test(parsedEmoji)) return parsedEmoji
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment