Klaus Kobald
How do I store global data/state in memory on nuxt server?
this is my socket code on the server.
import type { Peer, Message } from 'crossws'
import { peerManager } from '../peerManager'
export default defineWebSocketHandler({
open(peer) {
peerManager().addPeer(peer)
console.log('opened WS', peer)
// setInterval(() => {
// peer.send("server says: " + new Date())
// }, 1000)
},
close(peer) {
console.log('closed WS', peer)
peerManager().removePeer(peer)
},
error(peer, error) {
console.log('error on WS', peer, error)
},
message(peer, message) {
console.log('message on WS', peer, message)
}
})
The peerManager is supposed to hold all connections.
import type { Peer, Message } from 'crossws'
const room = 'ROOM'
const peers: Map<string, Peer> = new Map()
let activePeer: any = null
export const peerManager = () => {
const pushMessage = (msg: string) => {
console.log(msg, peers)
if (!activePeer) {
// if activePeer got deleted just pick any of the remainings
peers.forEach((p, k) => {
activePeer = p
})
}
if (activePeer)
activePeer.publish(room, msg)
}
const addPeer = (p: Peer) => {
peers.set(p.id, p)
console.log(peers)
p.subscribe(room)
activePeer = p
}
const removePeer = (p: Peer) => {
peers.delete(p.id)
console.log(peers)
p.unsubscribe(room)
activePeer = null
}
return {
pushMessage, addPeer, removePeer
}
}
But when I call pushMessage from another module the peerManagers properties are null.3 replies
How do I store global data/state in memory on nuxt server?
Hard to describe: Imagine a simple use case:
When Server starts it creates a timer that increases a variable count every second. As clients/peers connect they should all be able to get pushed the value of count when ever it changes. So assume best would be to be able for the client handler (on the server) to subscribe to this counter.
3 replies