javascript – Heartbeat pattern with Websocket in JS – annoyed by global dictionary


I’m implementing a kind of ‘heartbeat pattern’ with websocket in JS.

The idea is: the server keeps a dictionary holding a Websocket object for each uuid (an uuid is a client).

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
const DELAY_TO_DECLARE_DEATH_CLIENT = 15000

let websocketsDictionary = {}    
wss.on('connection', function connection(ws) {
        ws.on('message', function incoming(data) {
            data = JSON.parse(data)
            if(data.type == "REGISTER"){
                console.log("Client has registered to path " + data.path)
            }
            else if(data.type == "PUT"){
                console.log("Client says hello to " + data.path)
            }
            else if(data.type == "HEARTBEAT"){
                if(!websocketsDictionary(data.uuid)){
                    console.log("Remembering " + data.uuid)
                    websocketsDictionary(data.uuid) = {
                        ws: ws,
                        lastSeen: new Date().getTime()
                    }
                }
                else{
                    console.log("Already know " + data.uuid)
                    websocketsDictionary(data.uuid).lastSeen = new Date().getTime()
                }
            }
    
        })
    })

On the side, I’d like to purge each client that hasn’t sent a heartbeat in a certain threshold.

function purgeDeadClients(){
    let now =  new Date().getTime 
    websocketsDictionary = websocketsDictionary.filter(c => c.lastSeen - now < DELAY_TO_DECLARE_DEATH_CLIENT)
}

What I don’t like is that webosocketDictionary is global, and both the callbacks from ws.on and purgeDeadClients are reading/writing in it.

Is there some pattern I could use so that the content of websocketDictionary is shared by both callbacks, without being simply declared as global ?