mirror of
https://github.com/sergeyyarkov/educt-server.git
synced 2026-10-11 18:29:15 +03:00
fix: fixed session saving
This commit is contained in:
parent
d52cee9f57
commit
448d071f93
@ -26,7 +26,7 @@ export interface ClientToServerEvents {
|
||||
/**
|
||||
* User
|
||||
*/
|
||||
'user:logout': (data: { sessionId: string }) => void;
|
||||
'user:logout': () => void;
|
||||
}
|
||||
|
||||
export interface InterServerEvents {}
|
||||
@ -69,10 +69,13 @@ class WsService {
|
||||
const { sessionId, userId, userName } = socket.data;
|
||||
const isExistSocketData = !!(sessionId && userId && userName);
|
||||
|
||||
console.log('New socket connected');
|
||||
|
||||
/**
|
||||
* Set user session and send online count
|
||||
*/
|
||||
if (isExistSocketData) {
|
||||
console.log('Saving session');
|
||||
this.sessionStore
|
||||
.saveSession(sessionId, { userId, userName, connected: true })
|
||||
.then(() => this.sessionStore.getOnlineSessionsCount())
|
||||
@ -87,6 +90,13 @@ class WsService {
|
||||
*/
|
||||
socket.emit('user:session', { sessionId: socket.data.sessionId, userId: socket.data.userId });
|
||||
|
||||
/**
|
||||
* Destroy session on user logout request
|
||||
*/
|
||||
socket.on('user:logout', () => {
|
||||
console.log('Destroy session', sessionId);
|
||||
});
|
||||
|
||||
/**
|
||||
* Broadcast to all clients about new connection
|
||||
*/
|
||||
|
||||
@ -49,8 +49,13 @@ class RedisSessionStore {
|
||||
nextIndex = parseInt(nextIndexAsStr, 10);
|
||||
result.forEach(s => keys.add(s));
|
||||
} while (nextIndex !== 0);
|
||||
const commands = Array.from(keys).map(key => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const [prefix, ...id] = key.split('-');
|
||||
return ['hmget', id.join('-'), 'userId', 'userName', 'connected'];
|
||||
});
|
||||
|
||||
const commands = Array.from(keys).map(key => ['hmget', key.split('-')[1], 'userId', 'userName', 'connected']);
|
||||
console.log(commands);
|
||||
|
||||
return this.redisClient
|
||||
.multi(commands)
|
||||
@ -63,8 +68,8 @@ class RedisSessionStore {
|
||||
*/
|
||||
public async getOnlineSessionsCount() {
|
||||
const sessions = await this.getSessions();
|
||||
|
||||
const online = new Set(sessions.filter(s => s?.connected === true).map(s => s?.userId));
|
||||
|
||||
return online.size;
|
||||
}
|
||||
|
||||
@ -75,7 +80,7 @@ class RedisSessionStore {
|
||||
* @param data Session data
|
||||
*/
|
||||
public async saveSession(id: string, data: SessionDataType): Promise<void> {
|
||||
this.redisClient
|
||||
await this.redisClient
|
||||
.multi()
|
||||
.hmset(id, {
|
||||
userId: data.userId,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user