Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ws): mount multi ws servers on different paths #11188

Merged
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
19 changes: 12 additions & 7 deletions packages/platform-ws/adapters/ws-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { INestApplicationContext, Logger } from '@nestjs/common';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { isNil } from '@nestjs/common/utils/shared.utils';
import { normalizePath, isNil } from '@nestjs/common/utils/shared.utils';
import { AbstractWsAdapter } from '@nestjs/websockets';
import {
CLOSE_EVENT,
Expand Down Expand Up @@ -49,9 +49,13 @@ export class WsAdapter extends AbstractWsAdapter {

public create(
port: number,
options?: Record<string, any> & { namespace?: string; server?: any },
options?: Record<string, any> & {
namespace?: string;
server?: any;
path?: string;
},
) {
const { server, ...wsOptions } = options;
const { server, path, ...wsOptions } = options;
if (wsOptions?.namespace) {
const error = new Error(
'"WsAdapter" does not support namespaces. If you need namespaces in your project, consider using the "@nestjs/platform-socket.io" package instead.',
Expand All @@ -69,14 +73,14 @@ export class WsAdapter extends AbstractWsAdapter {
}),
);

this.addWsServerToRegistry(wsServer, port, options.path || '/');
this.addWsServerToRegistry(wsServer, port, path);
return wsServer;
}

if (server) {
return server;
}
if (options.path && port !== UNDERLYING_HTTP_SERVER_PORT) {
if (path && port !== UNDERLYING_HTTP_SERVER_PORT) {
// Multiple servers with different paths
// sharing a single HTTP/S server running on different port
// than a regular HTTP application
Expand All @@ -89,12 +93,13 @@ export class WsAdapter extends AbstractWsAdapter {
...wsOptions,
}),
);
this.addWsServerToRegistry(wsServer, port, options.path);
this.addWsServerToRegistry(wsServer, port, path);
return wsServer;
}
const wsServer = this.bindErrorHandler(
new wsPackage.Server({
port,
path,
...wsOptions,
}),
);
Expand Down Expand Up @@ -202,7 +207,7 @@ export class WsAdapter extends AbstractWsAdapter {
const entries = this.wsServersRegistry.get(port) ?? [];
entries.push(wsServer);

wsServer.path = path;
wsServer.path = normalizePath(path);
this.wsServersRegistry.set(port, entries);
}
}