mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
feat(ws): allow setting message parser in constructor
This commit is contained in:
@@ -245,6 +245,34 @@ describe('WebSocketGateway (WsAdapter)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should set messageParser by using constructor options', async () => {
|
||||
const testingModule = await Test.createTestingModule({
|
||||
providers: [ApplicationGateway],
|
||||
}).compile();
|
||||
app = testingModule.createNestApplication();
|
||||
|
||||
const wsAdapter = new WsAdapter(app, {
|
||||
messageParser: data => {
|
||||
const [event, payload] = JSON.parse(data.toString());
|
||||
return { event, data: payload };
|
||||
},
|
||||
});
|
||||
app.useWebSocketAdapter(wsAdapter);
|
||||
await app.listen(3000);
|
||||
|
||||
ws = new WebSocket('ws://localhost:8080');
|
||||
await new Promise(resolve => ws.on('open', resolve));
|
||||
|
||||
ws.send(JSON.stringify(['push', { test: 'test' }]));
|
||||
await new Promise<void>(resolve =>
|
||||
ws.on('message', data => {
|
||||
expect(JSON.parse(data).data.test).to.be.eql('test');
|
||||
ws.close();
|
||||
resolve();
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async function () {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
@@ -27,6 +27,9 @@ type WsServerRegistryKey = number;
|
||||
type WsServerRegistryEntry = any[];
|
||||
type WsData = string | Buffer | ArrayBuffer | Buffer[];
|
||||
type WsMessageParser = (data: WsData) => { event: string; data: any } | void;
|
||||
type WsAdapterOptions = {
|
||||
messageParser?: WsMessageParser;
|
||||
};
|
||||
|
||||
const UNDERLYING_HTTP_SERVER_PORT = 0;
|
||||
|
||||
@@ -47,9 +50,16 @@ export class WsAdapter extends AbstractWsAdapter {
|
||||
return JSON.parse(data.toString());
|
||||
};
|
||||
|
||||
constructor(appOrHttpServer?: INestApplicationContext | any) {
|
||||
constructor(
|
||||
appOrHttpServer?: INestApplicationContext | any,
|
||||
options?: WsAdapterOptions,
|
||||
) {
|
||||
super(appOrHttpServer);
|
||||
wsPackage = loadPackage('ws', 'WsAdapter', () => require('ws'));
|
||||
|
||||
if (options?.messageParser) {
|
||||
this.messageParser = options.messageParser;
|
||||
}
|
||||
}
|
||||
|
||||
public create(
|
||||
|
||||
Reference in New Issue
Block a user