How do I store global data/state in memory on nuxt server?
I have clients connecting via sockets to the nuxt server. I want that all connected clients get pushed live data from a datasource that the server is collecting. So I am storing all connecting peers in another global object - at least I am thinking it was global. But when I tell this object from another process to send/publish data to all the peers, the peer list is always empty. It seems as if that storage object is existing in different scopes.
Any thoughts on that?
1 Reply
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.
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.