Merge pull request #10545 from jmcdo29/feat/websocket-get-pattern

feat: create method on client to get websocket pattern
This commit is contained in:
Kamil Mysliwiec
2023-06-12 13:29:23 +02:00
committed by GitHub
8 changed files with 85 additions and 2 deletions

View File

@@ -66,5 +66,21 @@ describe('WebSocketGateway', () => {
);
});
it(`should be able to get the pattern in an interceptor`, async () => {
app = await createNestApp(ApplicationGateway);
await app.listen(3000);
ws = io('http://localhost:8080');
ws.emit('getClient', {
test: 'test',
});
await new Promise<void>(resolve =>
ws.on('popClient', data => {
expect(data.path).to.be.eql('getClient');
resolve();
}),
);
});
afterEach(() => app.close());
});

View File

@@ -194,6 +194,30 @@ describe('WebSocketGateway (WsAdapter)', () => {
});
});
it('should let the execution context have a getPattern() method on getClient()', async () => {
app = await createNestApp(ApplicationGateway);
await app.listen(3000);
ws = new WebSocket('ws://localhost:8080');
await new Promise(resolve => ws.on('open', resolve));
ws.send(
JSON.stringify({
event: 'getClient',
data: {
test: 'test',
},
}),
);
await new Promise<void>(resolve =>
ws.on('message', data => {
expect(JSON.parse(data).data.path).to.be.eql('getClient');
ws.close();
resolve();
}),
);
});
afterEach(async function () {
await app.close();
});

View File

@@ -1,8 +1,10 @@
import { UseInterceptors } from '@nestjs/common';
import {
MessageBody,
SubscribeMessage,
WebSocketGateway,
} from '@nestjs/websockets';
import { RequestInterceptor } from './request.interceptor';
@WebSocketGateway(8080)
export class ApplicationGateway {
@@ -13,4 +15,13 @@ export class ApplicationGateway {
data,
};
}
@UseInterceptors(RequestInterceptor)
@SubscribeMessage('getClient')
getPathCalled(client, data) {
return {
event: 'popClient',
data: { ...data, path: client.pattern },
};
}
}

View File

@@ -0,0 +1,11 @@
import { CallHandler, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
export class RequestInterceptor {
intercept(context: ExecutionContext, next: CallHandler) {
const client = context.switchToWs().getClient();
const pattern = context.switchToWs().getPattern();
client.pattern = pattern;
return next.handle();
}
}

View File

@@ -1,4 +1,6 @@
import { UseInterceptors } from '@nestjs/common';
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { RequestInterceptor } from './request.interceptor';
@WebSocketGateway()
export class ServerGateway {
@@ -9,4 +11,13 @@ export class ServerGateway {
data,
};
}
@UseInterceptors(RequestInterceptor)
@SubscribeMessage('getClient')
getPathCalled(client, data) {
return {
event: 'popClient',
data: { ...data, path: client.pattern },
};
}
}