-
Notifications
You must be signed in to change notification settings - Fork 235
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(session): allow using with crossws hooks (#960)
- Loading branch information
Showing
2 changed files
with
93 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { | ||
createApp, | ||
defineEventHandler, | ||
defineWebSocketHandler, | ||
useSession, | ||
type SessionConfig, | ||
} from "h3"; | ||
|
||
export const app = createApp(); | ||
|
||
const sessionConfig: SessionConfig = { | ||
password: "oee aaa ee o ee aa eeo ee aaa ee o ee", | ||
}; | ||
|
||
app.use( | ||
"/ws", | ||
defineWebSocketHandler({ | ||
async upgrade(request) { | ||
const session = await useSession(request, sessionConfig); | ||
console.log(`[upgrade] Session id: ${session.id}`); | ||
return {}; | ||
}, | ||
async open(peer) { | ||
const session = await useSession(peer, sessionConfig); | ||
console.log(`[open] Session id: ${session.id}`); | ||
peer.send(`Hello, ${session.id}!`); | ||
}, | ||
}), | ||
); | ||
|
||
app.use( | ||
defineEventHandler(async (event) => { | ||
// [IMPORTANT] Init the session before the first WebSocket upgrade | ||
const session = await useSession(event, sessionConfig); | ||
|
||
return /* html */ ` | ||
<div>Session id: ${session.id}</div> | ||
<pre id="output"></pre> | ||
<script type="module"> | ||
const log = (...args) => { | ||
console.log(...args); | ||
output.textContent += args.join(' ') + '\\n'; | ||
}; | ||
const output = document.getElementById('output'); | ||
const url = new URL('ws', location).href.replace(/^http/, 'ws') | ||
const ws = new WebSocket(url); | ||
ws.onopen = () => { log('[ws] Opened'); }; | ||
ws.onclose = () => { log('[ws] Closed'); }; | ||
ws.onmessage = (event) => { log('[ws] Message:', event.data); }; | ||
</script> | ||
`; | ||
}), | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters