Skip to content
This repository has been archived by the owner on Nov 10, 2022. It is now read-only.

Commit

Permalink
feat: remove inactive guests before sending the list
Browse files Browse the repository at this point in the history
Before emitting 'list-guests', remove the guests which 'expirationDate'
field is older than Date.now().
Also: refactor guests as a Map
  • Loading branch information
severo committed Jan 16, 2020
1 parent c0a04fb commit 45b0622
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,38 @@ const chat = io.on('connection', socket => {
})
})

let guests = []
const guests = new Map()
const setGuest = g => guests.set(g.sId, g)
const deleteGuest = id => guests.delete(id)
const getGuestsArray = () => [...guests.values()]
const timestamp = guest => {
const t = Date.now()
setGuest({ ...guest, updatedDate: t, expirationDate: t + 1000 * 60 * 10 })
}
const emitListGuests = () => {
// Clean the list, pruning guests that are inactive for more than 10min
const now = Date.now()
for ([id, g] of guests) {
if (!g.updatedDate || g.expirationDate < now) {
deleteGuest(id)
}
}
io.of('/occupapp-beta').emit('list-guests', getGuestsArray())
}
const occupappBeta = io.of('/occupapp-beta').on('connection', socket => {
console.log('New occupapp user connected')
socket.on('new-guest', (guest, ack) => {
guest.name = guest.name || `Guest_${new Date().getTime()}`
guest.name = guest.name || `Guest_${now()}`
guest.sId = socket.id
guest.color = rnd({ luminosity: 'dark' })
guests.push(guest)
io.of('/occupapp-beta').emit('list-guests', guests)
setGuest(guest)
timestamp(guest)
emitListGuests()
ack(guest)
})
socket.on('bye-bye', _ => {
guests = guests.filter(e => e.sId !== socket.id)
io.of('/occupapp-beta').emit('list-guests', guests)
deleteGuest(socket.id)
emitListGuests()
})
})

Expand Down

0 comments on commit 45b0622

Please sign in to comment.