-
-
Save brockbnntt/9f7f6df7936c602a2a63b947e1e1090b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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