diff --git a/partykit/server.ts b/partykit/server.ts index e03f8fe9..58bc4c9d 100644 --- a/partykit/server.ts +++ b/partykit/server.ts @@ -3,30 +3,18 @@ import { isValidEmoji } from '../shared/utils/emoji' export default { async onConnect (ws, party) { - // 1. handle live voting in slide deck - const setCount = async (val: number) => { - await party.storage.put('count', val) - ws.send(`count:${val}`) - } - + // 1. send current vote count if applicable ws.send(`count:${await getCount(party)}`) - ws.addEventListener('message', async ({ data }) => { - if (data === 'vote') await setCount((await getCount(party)) + 1) - if (data === 'clear') await setCount(0) - if (data === 'clear' && party.id === 'feedback') { - await party.storage.put('feedback', []) - ws.send(`feedback:[]`) - } - }) // 2. let everyone know someone new is viewing the site party.broadcast(`connections:${[...party.getConnections()].length}`) + // 3. send current feedback level if (party.id === 'feedback') { ws.send(`feedback:${JSON.stringify(await party.storage.get('feedback') || [])}`) } - // 3. let people know if I'm streaming + // 4. let people know if I'm streaming ws.send(`status:${(await party.storage.get('status')) || 'default'}`) }, async onRequest (request, party) { @@ -40,7 +28,7 @@ export default { emoji?: string } - // 4. allow one-off live voting via link + // 5. allow one-off live voting via link if (type === 'vote') { const val = (await getCount(party)) + 1 await party.storage.put('count', val) @@ -48,7 +36,7 @@ export default { return new Response(null, { status: 204 }) } - // 5. allow one-off live voting via link + // 6. allow one-off feedback submissions via link if (type === 'feedback') { await party.storage.transaction(async tx => { const feedback = await tx.get('feedback') || [] @@ -59,7 +47,7 @@ export default { return new Response(null, { status: 204 }) } - // 6. tell people if I'm going live + // 7. tell people if I'm going live if (type === 'status') { if (!status || !['live', 'default'].includes(status)) return new Response('Invalid status', { status: 422 }) @@ -75,10 +63,21 @@ export default { return new Response('Invalid request', { status: 422 }) }, async onMessage (message, ws, party) { - // Handle messages from WebSocket clients const messageStr = message.toString() - // Handle reaction messages + // 8. handle clearing votes from slide deck + if (messageStr === 'clear') { + if (party.id === 'feedback') { + await party.storage.put('feedback', []) + party.broadcast(`feedback:[]`) + } + else { + await party.storage.put('count', 0) + party.broadcast(`count:0`) + } + } + + // 7. handle reaction messages if (party.id === 'reactions' && messageStr.startsWith('reaction:')) { const emoji = messageStr.replace('reaction:', '')