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

feat(ws): add regex path support on platform ws path #13403

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions integration/websockets/e2e/ws-gateway.spec.ts
Expand Up @@ -9,6 +9,7 @@ import { ExamplePathGateway } from '../src/example-path.gateway';
import { ServerGateway } from '../src/server.gateway';
import { WsPathGateway } from '../src/ws-path.gateway';
import { WsPathGateway2 } from '../src/ws-path2.gateway';
import { WsPathGatewayRegex } from '../src/ws-path-regex.gateway';

async function createNestApp(...gateways): Promise<INestApplication> {
const testingModule = await Test.createTestingModule({
Expand Down Expand Up @@ -100,6 +101,36 @@ describe('WebSocketGateway (WsAdapter)', () => {
}
});

it(`should handle message on a regex path`, async () => {
app = await createNestApp(WsPathGatewayRegex);
await app.listen(3000);
try {
ws = new WebSocket('ws://localhost:3000/ws-path/randomRoomId');
await new Promise((resolve, reject) => {
ws.on('open', resolve);
ws.on('error', reject);
});

ws.send(
JSON.stringify({
event: 'push',
data: {
test: 'test',
},
}),
);
await new Promise<void>(resolve =>
ws.on('message', data => {
expect(JSON.parse(data).data.test).to.be.eql('test');
ws.close();
resolve();
}),
);
} catch (err) {
console.log(err);
}
});

it(`should support 2 different gateways running on different paths`, async function () {
this.retries(10);

Expand Down
14 changes: 14 additions & 0 deletions integration/websockets/src/ws-path-regex.gateway.ts
@@ -0,0 +1,14 @@
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';

@WebSocketGateway({
path: '/ws-path/:room_id',
})
export class WsPathGatewayRegex {
@SubscribeMessage('push')
onPush(client, data) {
return {
event: 'pop',
data,
};
}
}
19 changes: 10 additions & 9 deletions packages/platform-ws/adapters/ws-adapter.ts
@@ -1,6 +1,6 @@
import { INestApplicationContext, Logger } from '@nestjs/common';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { normalizePath, isNil } from '@nestjs/common/utils/shared.utils';
import { isNil, normalizePath } from '@nestjs/common/utils/shared.utils';
import { AbstractWsAdapter } from '@nestjs/websockets';
import {
CLOSE_EVENT,
Expand All @@ -9,7 +9,8 @@ import {
} from '@nestjs/websockets/constants';
import { MessageMappingProperties } from '@nestjs/websockets/gateway-metadata-explorer';
import * as http from 'http';
import { EMPTY, fromEvent, Observable } from 'rxjs';
import * as pathToRegex from 'path-to-regexp';
import { EMPTY, Observable, fromEvent } from 'rxjs';
import { filter, first, mergeMap, share, takeUntil } from 'rxjs/operators';

let wsPackage: any = {};
Expand Down Expand Up @@ -185,7 +186,9 @@ export class WsAdapter extends AbstractWsAdapter {

let isRequestDelegated = false;
for (const wsServer of wsServersCollection) {
if (pathname === wsServer.path) {
const pathMatchFn =
wsServer.path as pathToRegex.MatchFunction<object>;
if (pathMatchFn(pathname)) {
wsServer.handleUpgrade(request, socket, head, (ws: unknown) => {
wsServer.emit('connection', ws, request);
});
Expand All @@ -203,15 +206,13 @@ export class WsAdapter extends AbstractWsAdapter {
return httpServer;
}

protected addWsServerToRegistry<T extends Record<'path', string> = any>(
wsServer: T,
port: number,
path: string,
) {
protected addWsServerToRegistry<
T extends Record<'path', pathToRegex.MatchFunction<object>> = any,
>(wsServer: T, port: number, path: string) {
const entries = this.wsServersRegistry.get(port) ?? [];
entries.push(wsServer);

wsServer.path = normalizePath(path);
wsServer.path = pathToRegex.match(normalizePath(path));
this.wsServersRegistry.set(port, entries);
}
}
1 change: 1 addition & 0 deletions packages/platform-ws/package.json
Expand Up @@ -18,6 +18,7 @@
"access": "public"
},
"dependencies": {
"path-to-regexp": "^6.2.1",
"tslib": "2.6.2",
"ws": "8.16.0"
},
Expand Down