Skip to content

Commit

Permalink
feat(ws): add regex path support on platform ws path
Browse files Browse the repository at this point in the history
  • Loading branch information
RavenColEvol committed Apr 5, 2024
1 parent 8b4dbb3 commit aa8ce25
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 9 deletions.
31 changes: 31 additions & 0 deletions integration/websockets/e2e/ws-gateway.spec.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
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 { 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
Original file line number Diff line number Diff line change
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

0 comments on commit aa8ce25

Please sign in to comment.