How to pass data on request upgrade?
#6
-
|
In regular bun server, you can attach user data to the ws handler using Also, export async function GET({ platform, cookies }) {
const session = cookies.get("session");
const username = await getUsernameFromSession(session);
return platform!.markForUpgrade(
new Response('Websocket Required', {
status: 400
}),
// Note the function instead of object here (proposal)..
function handler(server) {
return {
open: (ws) => {
console.log(ws.data.username);
server.publish("chat", `"${ws.data.username}" connected.`);
},
// ...
}
},
// Attaching the data as the third argument (proposal)..
{
data: { username },
},
);
}As a workaround, i could pass the data directly to my handler function and attach it to the export async function GET({ platform, cookies }) {
const session = cookies.get("session");
const username = await getUsernameFromSession(session);
return platform!.markForUpgrade(
new Response('Websocket Required', {
status: 400
}),
// a function returning current handler object..
handler(
// postponing the data, attaching to the `ws.data` later within `handler.open`
{
data: { username },
}
),
);
}The problem with this workaround is, that the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
the handler itself is already the data itself export async function GET({ platform, cookies }) {
const session = cookies.get("session");
const username = await getUsernameFromSession(session);
return platform!.markForUpgrade(
new Response('Websocket Required', {
status: 400
}),
{
username,
open(ws) {
console.log(ws.data === this); // => true
ws.send(`Hello ${this.username}`); // use either this.username or ws.data.username, both work
// even `Hello ${username}` would just work since username exists in this scope
}
}
);
}if you want to avoid unwanted variable kept in the scope, here is another approach class Greeting {
#username: string;
constructor(username: string) {
this.#username = username;
}
open(ws) {
ws.send(`Hello ${this.#username}`);
}
}
export async function GET({ platform, cookies }) {
const session = cookies.get("session");
const username = await getUsernameFromSession(session);
return platform!.markForUpgrade(
new Response('Websocket Required', {
status: 400
}),
new Greeting(username)
);
}Why design like this? (if you wonder) sveltekit-adapter-bun/src/files/index.ts Line 42 in 218456f |
Beta Was this translation helpful? Give feedback.
the handler itself is already the data itself
if you want to avoid unwanted variable kept in the scope, here is another approach