Skip to content

Commit c2c6a3d

Browse files
committed
docs(ws): update message parser usage
1 parent 4de04f1 commit c2c6a3d

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

content/websockets/adapter.md

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,20 @@ app.useWebSocketAdapter(new WsAdapter(app));
9494

9595
> info **Hint** The `WsAdapter` is imported from `@nestjs/platform-ws`.
9696
97-
The `wsAdapter` can only route messages in the `{ event: string, data: any }` format. If you need to receive and process messages in other formats, you should set up an appropriate message preprocessor to convert the messages into the `{ event: string, data: any }` format.
97+
The `wsAdapter` can only route messages in the `{{ '{' }} event: string, data: any {{ '}' }}` format. If you need to receive and process messages in other formats, you should set up an appropriate message parser to convert the messages into the `{{ '{' }} event: string, data: any {{ '}' }}` format.
9898

9999
```typescript
100-
const wsAdapter = new WsAdapter(app);
101-
102-
// to process [event, ...data] format messages
103-
wsAdapter.setMessagePreprocessor((message: any) => {
104-
const [event, ...data] = message;
105-
return { event, data };
100+
const wsAdapter = new WsAdapter(app, {
101+
// to process [event, data] format messages
102+
messageParser: (data) => {
103+
const [event, payload] = JSON.parse(data.toString());
104+
return { event, data: payload };
105+
},
106106
});
107107
```
108108

109+
You can also set up after the adapter is created using the `setMessageParser` method.
110+
109111
#### Advanced (custom adapter)
110112

111113
For demonstration purposes, we are going to integrate the [ws](https://github.com/websockets/ws) library manually. As mentioned, the adapter for this library is already created and is exposed from the `@nestjs/platform-ws` package as a `WsAdapter` class. Here is how the simplified implementation could potentially look like:

0 commit comments

Comments
 (0)