socket.io-react-hooks-advanced
Version:
A modular and extensible React + Socket.IO hook library designed for real-world applications. Supports namespaced sockets, reconnection strategies, offline queues, latency monitoring, middleware, encryption, and more.
37 lines (36 loc) • 1.19 kB
JavaScript
import { decryptAES, encryptAES } from "../utils/encryption";
export const encryptionPlugin = ({ secretKey, encryptEvents = [], decryptEvents = [], }) => {
const emitMiddleware = (event, data, next) => {
if (encryptEvents.includes(event)) {
try {
const plaintext = JSON.stringify(data);
const encrypted = encryptAES(plaintext, secretKey);
next(event, encrypted);
}
catch (err) {
console.error("Encryption error:", err);
next(event, data);
}
}
else {
next(event, data);
}
};
const onMiddleware = (event, data, next) => {
if (decryptEvents.includes(event)) {
try {
const decryptedStr = decryptAES(data, secretKey);
const decryptedData = JSON.parse(decryptedStr);
next(decryptedData);
}
catch (err) {
console.error("Decryption error:", err);
next(data);
}
}
else {
next(data);
}
};
return { emitMiddleware, onMiddleware };
};