Skip to content

Commit

Permalink
refactor: getSocket and getSockets works directly with this.userS…
Browse files Browse the repository at this point in the history
…ockets as redis is initialized at the beginning
  • Loading branch information
IamLizu committed Oct 30, 2024
1 parent f7c7a66 commit 885cd16
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 111 deletions.
5 changes: 5 additions & 0 deletions History.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# History

## Unreleased

- Refactor `getSockets` to return `this.userSockets` directly instead of using Redis.
- Refactor `getSocket` to return `this.userSockets.get(userId)` directly instead of using Redis.

## v1.0.1

- Clean `registerSocketForUser` method
Expand Down
73 changes: 24 additions & 49 deletions src/SockManage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { RedisClientType } from 'redis';
import { Namespace, Socket, Server as SocketIOServer } from 'socket.io';
import { deprecate } from 'util';
import { RedisClientType } from "redis";
import { Namespace, Socket, Server as SocketIOServer } from "socket.io";
import { deprecate } from "util";

interface SocketManagerOptions {
redis: RedisClientType;
Expand Down Expand Up @@ -87,7 +87,7 @@ export class SockManage {
*/
setup({ io, namespace }: SetupOptions): void {
this.io = io;
this.namespace = namespace ? this.io.of(namespace) : this.io.of('/');
this.namespace = namespace ? this.io.of(namespace) : this.io.of("/");
}

/**
Expand All @@ -97,7 +97,7 @@ export class SockManage {
* @returns {Promise<void>} A promise that resolves when the user sockets have been initialized.
*/
async initialize(): Promise<void> {
let userSockets = await this.redis.get('userSockets');
let userSockets = await this.redis.get("userSockets");

if (userSockets) {
this.userSockets = new Map(JSON.parse(userSockets));
Expand All @@ -109,67 +109,42 @@ export class SockManage {
*/
initializeUserSockets = deprecate(
this.initialize,
'initializeUserSockets() is deprecated. Use initialize() instead.'
"initializeUserSockets() is deprecated. Use initialize() instead."
);

/**
* Retrieves the user sockets from Redis.
* Retrieves the map of user sockets.
*
* @returns {Promise<Map<string, string> | null>} A promise that resolves to a Map of user sockets if available, or null if not found or an error occurs.
*
* @throws Will log an error message if there is an issue retrieving or parsing the user sockets from Redis.
* @returns {Map<string, string>} A map where the keys are user identifiers and the values are socket identifiers.
*/
async getSockets(): Promise<Map<string, string> | null> {
try {
let userSockets = await this.redis.get('userSockets');

if (userSockets) {
try {
return new Map(JSON.parse(userSockets));
} catch (error) {
console.error(
'Failed to parse userSockets from Redis:',
error
);

return null;
}
}

return null;
} catch (error) {
console.error('Error retrieving userSockets from Redis:', error);

return null;
}
getSockets(): Map<string, string> {
return this.userSockets;
}

/**
* @deprecated Use `getSockets` instead.
*/
getUserSockets = deprecate(
this.getSockets,
'getUserSockets() is deprecated. Use getSockets() instead.'
"getUserSockets() is deprecated. Use getSockets() instead."
);

/**
* Retrieves the socket ID associated with a given user ID.
* Retrieves the socket ID associated with a user.
*
* @param userId - The unique identifier of the user.
* @returns A promise that resolves to the socket ID as a string if found, or null if not found.
* @returns The socket ID if found, otherwise `null`.
*/
async getSocket(userId: string): Promise<string | null> {
const userSockets = await this.getSockets();

return userSockets ? userSockets.get(userId) || null : null;
getSocket(userId: string): string | null {
return this.userSockets.get(userId) || null;
}

/**
* @deprecated Use `getSocket` instead.
*/
getUserSocket = deprecate(
this.getSocket,
'getUserSocket() is deprecated. Use getSocket() instead.'
"getUserSocket() is deprecated. Use getSocket() instead."
);

/**
Expand All @@ -184,7 +159,7 @@ export class SockManage {
const userId = this.extractUserId(data);

if (!userId) {
throw new Error('userId not found in data, it is required!');
throw new Error("userId not found in data, it is required!");
}

await this.handleExistingConnection(userId, socket);
Expand All @@ -198,7 +173,7 @@ export class SockManage {
*/
registerSocketForUser = deprecate(
this.register,
'registerSocketForUser() is deprecated. Use register() instead.'
"registerSocketForUser() is deprecated. Use register() instead."
);

/**
Expand All @@ -214,7 +189,7 @@ export class SockManage {

return parsedData.userId || null;
} catch (error) {
console.error('Failed to parse user data:', error);
console.error("Failed to parse user data:", error);
return null;
}
}
Expand Down Expand Up @@ -252,11 +227,11 @@ export class SockManage {
private async saveUserSocketsToRedis(): Promise<void> {
try {
await this.redis.set(
'userSockets',
"userSockets",
JSON.stringify(Array.from(this.userSockets.entries()))
);
} catch (error) {
console.error('Failed to persist user sockets in Redis:', error);
console.error("Failed to persist user sockets in Redis:", error);
}
}

Expand All @@ -283,7 +258,7 @@ export class SockManage {
*/
deRegisterSocketForUser = deprecate(
this.deRegister,
'deRegisterSocketForUser() is deprecated. Use deRegister() instead.'
"deRegisterSocketForUser() is deprecated. Use deRegister() instead."
);

/**
Expand All @@ -297,7 +272,7 @@ export class SockManage {
* @returns {void}
*/
inform({
namespace = '/',
namespace = "/",
socketId,
_event,
data,
Expand All @@ -310,6 +285,6 @@ export class SockManage {
*/
informSocket = deprecate(
this.inform,
'informSocket() is deprecated. Use inform() instead.'
"informSocket() is deprecated. Use inform() instead."
);
}
Loading

0 comments on commit 885cd16

Please sign in to comment.