/clients.ts Secret
Created
June 9, 2024 02:14
Cloudflare durable objects
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
// Get all previous clients | |
const previousClients = await this.ctx.storage.get<Map<string, WebSocket>>('clients'); | |
if (previousClients) { | |
console.log('Found previous clients'); | |
this.clients = previousClients; | |
} |
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
import { Env } from '../index'; | |
export async function sendQueuedMessage(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { | |
const matchmakerInstanceId = ctx.params.matchmakerId; | |
// Use the matchmakerId to find the Durable Object instance | |
const id = env.MM_DURABLE_OBJECT.idFromString(matchmakerInstanceId); | |
let stub = env.MM_DURABLE_OBJECT.get(id); | |
const validInstance = await stub.instanceValid(); | |
const clientAmount = await stub.clientAmount; | |
if (!validInstance || clientAmount === 0) { | |
const responseMessage = !validInstance ? { error: 'Uninitialized matchmaking instance' } : { message: 'No clients connected' }; | |
const status = !validInstance ? 400 : 200; | |
return new Response(JSON.stringify(responseMessage), { status, headers: { 'Content-Type': 'application/json' } }); | |
} | |
await stub.sendQueued(); | |
return new Response(JSON.stringify({ message: 'Message sent' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment