ws_test.js 866 B

1234567891011121314151617181920212223242526272829303132
  1. const baseUrl = process.env.BASE_URL || "http://127.0.0.1:8787";
  2. const graphId = process.env.GRAPH_ID || "dev-graph";
  3. const wsUrl = baseUrl.replace(/^http/, "ws") + `/sync/${graphId}`;
  4. const WebSocketCtor = globalThis.WebSocket;
  5. if (!WebSocketCtor) {
  6. console.error("WebSocket not available. Use node>=20 or provide a WebSocket polyfill.");
  7. process.exit(1);
  8. }
  9. const ws = new WebSocketCtor(wsUrl);
  10. let pending = 0;
  11. ws.addEventListener("open", () => {
  12. ws.send(JSON.stringify({ type: "hello", client: "ws-test" }));
  13. ws.send(JSON.stringify({ type: "ping" }));
  14. ws.send(JSON.stringify({ type: "pull", since: 0 }));
  15. pending = 3;
  16. });
  17. ws.addEventListener("message", (event) => {
  18. console.log(String(event.data));
  19. pending -= 1;
  20. if (pending <= 0) {
  21. ws.close();
  22. }
  23. });
  24. ws.addEventListener("error", (event) => {
  25. console.error("ws error", event);
  26. });