feat(ws): allow setting message parser in constructor

This commit is contained in:
codytseng
2024-11-13 09:58:32 +08:00
parent 2ab99739cd
commit 33e32d9d5d
2 changed files with 39 additions and 1 deletions

View File

@@ -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();
});

View File

@@ -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(