Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/engine.io/lib/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -669,13 +669,17 @@ export abstract class BaseServer extends EventEmitter {
*
* @see https://nodejs.org/api/http.html#class-httpserverresponse
*/
class WebSocketResponse {
class WebSocketResponse extends EventEmitter {
constructor(
readonly req,
readonly socket: Duplex,
) {
super();
// temporarily store the response headers on the req object (see the "headers" event)
req[kResponseHeaders] = {};
// some middlewares (like pino-http) rely on the "close" event to know when the response is done, which the
// underlying socket does not expose by default
socket.once("close", () => this.emit("close"));
}

public setHeader(name: string, value: any) {
Expand All @@ -695,6 +699,7 @@ class WebSocketResponse {
public writeHead() {}

public end() {
this.emit("finish");
// we could return a proper error code, but the WebSocket client will emit an "error" event anyway.
this.socket.destroy();
}
Expand Down
23 changes: 23 additions & 0 deletions packages/engine.io/test/middlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,29 @@ describe("middlewares", () => {
});
});

it("should expose EventEmitter methods on the response object during upgrade (regression for pino-http)", (done) => {
const engine = listen((port) => {
engine.use((req, res, next) => {
expect(res.on).to.be.a("function");
res.on("close", () => {
if (engine.httpServer) {
engine.httpServer.close();
}
done();
});
next();
});

const socket = new WebSocket(
`ws://localhost:${port}/engine.io/?EIO=4&transport=websocket`,
);

socket.on("open", () => {
socket.close();
});
});
});

it("should apply all middlewares in order", (done) => {
const engine = listen((port) => {
let count = 0;
Expand Down