Testing websocket client

This commit is contained in:
2026-02-15 23:55:54 +01:00
parent be2c27093c
commit 4520eaf861
3 changed files with 120 additions and 45 deletions
+84 -43
View File
@@ -1,16 +1,78 @@
import axios from "axios";
import { WebSocket } from "ws";
import { LiveRunMove } from "./types";
import { randomUUID } from "crypto";
var cookies: string | undefined;
let socket: WebSocket | null = null;
let cookies: string | undefined;
type PendingResolver = {
resolve: (value: any) => void;
reject: (err: any) => void;
};
const pending = new Map<string, PendingResolver>();
export function getCookies(): string | undefined {
return cookies;
}
export function setCookies(c: string) {
cookies = c;
}
function getOrigin(useLocalhost: boolean) {
return useLocalhost ? "http://localhost:3000" : "https://dev-run.selimaj.dev";
function getWsOrigin(useLocalhost: boolean) {
return useLocalhost
? "ws://localhost:3000/api/run"
: "wss://dev-run.selimaj.dev/api/run";
}
function ensureSocket(useLocalhost: boolean): WebSocket {
if (socket && socket.readyState === WebSocket.OPEN) {
return socket;
}
socket = new WebSocket(getWsOrigin(useLocalhost));
socket.onmessage = (e) => {
const msg = JSON.parse(e.data.toString());
const { requestId, ok, data, error } = msg;
if (!requestId) return;
const pendingReq = pending.get(requestId);
if (!pendingReq) return;
pending.delete(requestId);
ok ? pendingReq.resolve(data) : pendingReq.reject(error);
};
socket.onclose = () => {
socket = null;
};
return socket;
}
function send<T>(
useLocalhost: boolean,
payload: Record<string, any>,
): Promise<T> {
return new Promise((resolve, reject) => {
const ws = ensureSocket(useLocalhost);
const requestId = randomUUID();
pending.set(requestId, { resolve, reject });
ws.send(
JSON.stringify({
...payload,
requestId,
cookies, // optional: only needed if you authenticate via cookies manually
}),
);
});
}
export async function addRun(
@@ -18,34 +80,20 @@ export async function addRun(
problem: string,
mode: string,
): Promise<string> {
return (
await axios.put(
getOrigin(useLocalhost) + "/api/run",
{
problem,
category: mode,
},
{
headers: {
Cookie: cookies,
},
},
)
).data.runId;
const data = await send<{ runId: string }>(useLocalhost, {
type: "create",
problem,
category: mode,
});
return data.runId;
}
export async function submitRun(useLocalhost: boolean, runId: string) {
await axios.post(
getOrigin(useLocalhost) + "/api/run",
{
runId,
},
{
headers: {
Cookie: cookies,
},
},
);
await send(useLocalhost, {
type: "submit",
runId,
});
}
export async function addRunMoves(
@@ -55,18 +103,11 @@ export async function addRunMoves(
language: string | null,
moves: LiveRunMove[],
) {
await axios.post(
getOrigin(useLocalhost) + "/api/run/move",
{
runId,
file,
moves,
language,
},
{
headers: {
Cookie: cookies,
},
},
);
await send(useLocalhost, {
type: "move",
runId,
file,
language,
moves,
});
}