Skip to content

Commit

Permalink
fix: properly track updates to socket.data
Browse files Browse the repository at this point in the history
Before this commit, attributes added to `socket.data` within a
middleware were lost.

Related: 3773fe4
  • Loading branch information
C1200 authored and darrachequesne committed May 3, 2022
1 parent 4359536 commit e17e9e1
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,13 +321,19 @@ const registerListeners = (
});
};

const data = socket.data || {}; // could be set in a middleware

socket.data = createProxy({
_admin: {
clientId: clientId.substring(0, 12), // this information is quite sensitive
transport: socket.conn.transport.name,
},
});

for (const key in data) {
socket.data[key] = createProxy(data[key]);
}

adminNamespace.emit("socket_connected", serialize(socket, nsp.name));

socket.conn.on("upgrade", (transport: any) => {
Expand Down
40 changes: 40 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,46 @@ describe("Socket.IO Admin (server instrumentation)", () => {
adminSocket.disconnect();
});

it("emits event when socket.data is updated", async () => {
instrument(io, {
auth: false,
});

const adminSocket = ioc(`http://localhost:${port}/admin`);

await waitFor(adminSocket, "connect");

const clientSocket = ioc(`http://localhost:${port}`, {
forceNew: true,
transports: ["polling"],
});

io.use((socket, next) => {
socket.data = socket.data || {};
socket.data.count = 1;
socket.data.array = [1];
next();
});

const serverSocket = await waitFor(io, "connection");

const socket = await waitFor(adminSocket, "socket_connected");
expect(socket.data).to.eql({ count: 1, array: [1] });

serverSocket.data.count++;

const updatedSocket1 = await waitFor(adminSocket, "socket_updated");
expect(updatedSocket1.data).to.eql({ count: 2, array: [1] });

serverSocket.data.array.push(2);

const updatedSocket2 = await waitFor(adminSocket, "socket_updated");
expect(updatedSocket2.data).to.eql({ count: 2, array: [1, 2] });

adminSocket.disconnect();
clientSocket.disconnect();
});

it("performs administrative tasks", async () => {
instrument(io, {
auth: false,
Expand Down

0 comments on commit e17e9e1

Please sign in to comment.