Skip to content

Instantly share code, notes, and snippets.

@simplyzetax
Created June 9, 2024 02:14
Cloudflare durable objects
// 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;
}
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