Skip to content

Commit e17e9e1

Browse files
C1200darrachequesne
authored andcommitted
fix: properly track updates to socket.data
Before this commit, attributes added to `socket.data` within a middleware were lost. Related: 3773fe4
1 parent 4359536 commit e17e9e1

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

lib/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,13 +321,19 @@ const registerListeners = (
321321
});
322322
};
323323

324+
const data = socket.data || {}; // could be set in a middleware
325+
324326
socket.data = createProxy({
325327
_admin: {
326328
clientId: clientId.substring(0, 12), // this information is quite sensitive
327329
transport: socket.conn.transport.name,
328330
},
329331
});
330332

333+
for (const key in data) {
334+
socket.data[key] = createProxy(data[key]);
335+
}
336+
331337
adminNamespace.emit("socket_connected", serialize(socket, nsp.name));
332338

333339
socket.conn.on("upgrade", (transport: any) => {

test/index.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,46 @@ describe("Socket.IO Admin (server instrumentation)", () => {
300300
adminSocket.disconnect();
301301
});
302302

303+
it("emits event when socket.data is updated", async () => {
304+
instrument(io, {
305+
auth: false,
306+
});
307+
308+
const adminSocket = ioc(`http://localhost:${port}/admin`);
309+
310+
await waitFor(adminSocket, "connect");
311+
312+
const clientSocket = ioc(`http://localhost:${port}`, {
313+
forceNew: true,
314+
transports: ["polling"],
315+
});
316+
317+
io.use((socket, next) => {
318+
socket.data = socket.data || {};
319+
socket.data.count = 1;
320+
socket.data.array = [1];
321+
next();
322+
});
323+
324+
const serverSocket = await waitFor(io, "connection");
325+
326+
const socket = await waitFor(adminSocket, "socket_connected");
327+
expect(socket.data).to.eql({ count: 1, array: [1] });
328+
329+
serverSocket.data.count++;
330+
331+
const updatedSocket1 = await waitFor(adminSocket, "socket_updated");
332+
expect(updatedSocket1.data).to.eql({ count: 2, array: [1] });
333+
334+
serverSocket.data.array.push(2);
335+
336+
const updatedSocket2 = await waitFor(adminSocket, "socket_updated");
337+
expect(updatedSocket2.data).to.eql({ count: 2, array: [1, 2] });
338+
339+
adminSocket.disconnect();
340+
clientSocket.disconnect();
341+
});
342+
303343
it("performs administrative tasks", async () => {
304344
instrument(io, {
305345
auth: false,

0 commit comments

Comments
 (0)