dandoen
dandoen
CDCloudflare Developers
Created by dandoen on 1/15/2025 in #durable-objects
hi folks,
oh nice, thank you.. did not see serialize/deserialize
6 replies
CDCloudflare Developers
Created by dandoen on 1/15/2025 in #durable-objects
hi folks,
any push in the right direction would be appreciated!
6 replies
CDCloudflare Developers
Created by dandoen on 1/15/2025 in #durable-objects
hi folks,
// Durable Object
export default class WebSocketHibernationServer extends DurableObject {
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}

// Extract userId from the protocol
const wsProtocol = request.headers.get('Sec-WebSocket-Protocol');
const [protocol] = wsProtocol?.split(', ') || [];

console.log('server', { protocol });

const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);

this.ctx.acceptWebSocket(server);

return new Response(null, {
status: 101,
headers: {
Upgrade: 'websocket',
Connection: 'Upgrade',
'Sec-WebSocket-Protocol': protocol || '',
},
webSocket: client,
});
}

async webSocketMessage(ws: WebSocket, message: ArrayBuffer | string) {
// TODO: How do we get the user ID from the websocket?

const websockets = this.ctx.getWebSockets();
for (const ws of websockets) {
ws.send(message);
}
}

async webSocketClose(ws: WebSocket, code: number, reason: string, _wasClean: boolean) {
ws.close(code, reason);
}
}
// Durable Object
export default class WebSocketHibernationServer extends DurableObject {
async fetch(request: Request): Promise<Response> {
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}

// Extract userId from the protocol
const wsProtocol = request.headers.get('Sec-WebSocket-Protocol');
const [protocol] = wsProtocol?.split(', ') || [];

console.log('server', { protocol });

const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);

this.ctx.acceptWebSocket(server);

return new Response(null, {
status: 101,
headers: {
Upgrade: 'websocket',
Connection: 'Upgrade',
'Sec-WebSocket-Protocol': protocol || '',
},
webSocket: client,
});
}

async webSocketMessage(ws: WebSocket, message: ArrayBuffer | string) {
// TODO: How do we get the user ID from the websocket?

const websockets = this.ctx.getWebSockets();
for (const ws of websockets) {
ws.send(message);
}
}

async webSocketClose(ws: WebSocket, code: number, reason: string, _wasClean: boolean) {
ws.close(code, reason);
}
}
6 replies
CDCloudflare Developers
Created by dandoen on 1/15/2025 in #durable-objects
hi folks,
// This gets called in my fetch handler
/*
if (request.url.includes('/websocket')) {
return handleWebsocketRequest(request, env, appUrl, user);
}
*/
export const handleWebsocketRequest = async (
request: Request,
env: Env,
appUrl: string,
user: User | null,
): Promise<Response> => {
if (request.url.includes('/websocket') && user) {
let id = env.WEBSOCKET_HIBERNATION_SERVER.idFromName(`user-${user?.id}`);
let stub = env.WEBSOCKET_HIBERNATION_SERVER.get(id);
// Let the Durable Object handle the WebSocket creation and upgrade
const response = await stub.fetch(request.url, {
method: request.method,
headers: request.headers,
body: request.body,
});

return response as Response;
}

return new Response(
JSON.stringify({
error: {
code: 'Unauthorized',
message: 'You must be logged in to use this endpoint',
},
}),
{
status: 401,
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin': appUrl,
'Access-Control-Allow-Credentials': 'true',
},
},
);
};
// This gets called in my fetch handler
/*
if (request.url.includes('/websocket')) {
return handleWebsocketRequest(request, env, appUrl, user);
}
*/
export const handleWebsocketRequest = async (
request: Request,
env: Env,
appUrl: string,
user: User | null,
): Promise<Response> => {
if (request.url.includes('/websocket') && user) {
let id = env.WEBSOCKET_HIBERNATION_SERVER.idFromName(`user-${user?.id}`);
let stub = env.WEBSOCKET_HIBERNATION_SERVER.get(id);
// Let the Durable Object handle the WebSocket creation and upgrade
const response = await stub.fetch(request.url, {
method: request.method,
headers: request.headers,
body: request.body,
});

return response as Response;
}

return new Response(
JSON.stringify({
error: {
code: 'Unauthorized',
message: 'You must be logged in to use this endpoint',
},
}),
{
status: 401,
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin': appUrl,
'Access-Control-Allow-Credentials': 'true',
},
},
);
};
6 replies
TtRPC
Created by Emil on 1/3/2025 in #❓-help
subscriptions on edge
I’m also battling this currently. What are you running into? I ran into: https://github.com/trpc/trpc/issues/6360
2 replies
TtRPC
Created by cruhl on 4/10/2024 in #❓-help
Does anyone have an example of subscriptions implemented in CloudFlare Workers?
8 replies
TtRPC
Created by cruhl on 4/10/2024 in #❓-help
Does anyone have an example of subscriptions implemented in CloudFlare Workers?
Same.. @cruhl any chance you'd be willing to share the high level?
8 replies
TtRPC
Created by Emil on 12/8/2024 in #❓-help
Getting type error for AppRouter
Mine was an old typescript version!
4 replies
TtRPC
Created by Emil on 12/8/2024 in #❓-help
Getting type error for AppRouter
hey, i'm running into this same exact thing. did you figure it out? EDIT: clearing node_modules did the trick 😬
4 replies