Access to websocket object
walmartwarlord opened this issue · comments
Describe the feature
Hi, I'm looking at the new WebSocket feature and wondering how we can do stuff like peer.send("pong");
but inside an api route? Is it also possible to access the WebSocket object outside _ws.ts
for example so we can play with it outside the defineWebSocketHandler
?
Is there a better way of doing it other than this?
// lib/ee.ts
export const ee = new EventEmitter();
// server/api/todo.post.ts
import { ee } from '~/lib/ee'
export default defineEventHandler(() => {
const todo = await addTodo({})
ee.emit('add', todo)
})
// server/routes/_ws.ts
import { ee } from '~/lib/ee'
export default defineWebSocketHandler({
message(peer) {
ee.on('add', (todo) => {
peer.send(todo)
})
},
});
Couldn't this potentially lead to a leakage of request context.
For example, the eventEmitter util imported always stays the same, but the event and ctx/scope is recreated for each request. This could make every random request, call the emitter, thus passing data of a user/client to another connected WebSocket end.
I see what you mean @CHIBX. Do you have any advice on doing this approach?
I see what you mean @CHIBX. Do you have any advice on doing this approach?
@walmartwarlord I do have an idea, but it all depends on your application needs.
I have no idea what your server code is trying to achieve, but from the above code I could guess that you might be trying to show a particular user's todo to another user connected to the socket, much like a global viewable todo book.
I also don't think you should add the event listener in the message method but instead in the open method, because I guess the function that you append seems to be different every single time, possible increasing memory in proportion to incoming socket messages, and you could also kinda clear the function after closing the socket to prevent holding reference to the peer object