Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add websocket support utils, and app handling #544

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,16 @@
"test:types": "vitest typecheck"
},
"dependencies": {
"@types/ws": "^8.5.5",
"cookie-es": "^1.0.0",
"defu": "^6.1.2",
"destr": "^2.0.1",
"iron-webcrypto": "^0.10.1",
"radix3": "^1.1.0",
"ufo": "^1.3.0",
"uncrypto": "^0.1.3",
"unenv": "^1.7.4"
"unenv": "^1.7.4",
"ws": "^8.14.2"
},
"devDependencies": {
"0x": "^5.6.0",
Expand Down
37 changes: 30 additions & 7 deletions playground/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
import { createApp, createRouter, eventHandler } from "h3";

import {
createApp,
eventHandler,
upgradeWebSocket,
isWebSocketUpgradeRequest,
isWebSocketEvent,
toWebSocketEvent,
} from "h3";
export const app = createApp();

const router = createRouter();
app.use(router);

router.get(
app.use(
"/",
eventHandler((event) => {
return { path: event.path, message: "Hello World!" };
if (isWebSocketEvent(event)) {
const wsEvent = toWebSocketEvent(event);
if (wsEvent.type === "connection") {
wsEvent.connection.send("pong");
} else if (wsEvent.type === "message") {
console.log("got", new TextDecoder().decode(wsEvent.message));
}
}
if (isWebSocketUpgradeRequest(event)) {
return upgradeWebSocket(event);
}

return `<h1>Hello World!</h1><script type="module">
const ws = new WebSocket("ws://localhost:3000");
await new Promise((resolve) => ws.addEventListener("open", resolve));
ws.addEventListener("message", (event) => {
console.log(event.data);
ws.send("ping from client");
});
ws.send("pong");
</script>`;
}),
);
60 changes: 58 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading