Skip to content

Commit 2a319c1

Browse files
Merge pull request #2210 from Tony133/docs/update-websockets
docs(websockets): update for extend socket.io
2 parents 8a1d75e + cd8ced1 commit 2a319c1

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

content/websockets/adapter.md

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,25 +30,32 @@ The WebSockets module is platform-agnostic, hence, you can bring your own librar
3030
The [socket.io](https://github.com/socketio/socket.io) package is wrapped in an `IoAdapter` class. What if you would like to enhance the basic functionality of the adapter? For instance, your technical requirements require a capability to broadcast events across multiple load-balanced instances of your web service. For this, you can extend `IoAdapter` and override a single method which responsibility is to instantiate new socket.io servers. But first of all, let's install the required package.
3131

3232
```bash
33-
$ npm i --save socket.io-redis
33+
$ npm i --save redis socket.io @socket.io/redis-adapter
3434
```
3535

3636
Once the package is installed, we can create a `RedisIoAdapter` class.
3737

3838
```typescript
3939
import { IoAdapter } from '@nestjs/platform-socket.io';
40-
import { RedisClient } from 'redis';
4140
import { ServerOptions } from 'socket.io';
42-
import { createAdapter } from 'socket.io-redis';
43-
44-
const pubClient = new RedisClient({ host: 'localhost', port: 6379 });
45-
const subClient = pubClient.duplicate();
46-
const redisAdapter = createAdapter({ pubClient, subClient });
41+
import { createAdapter } from '@socket.io/redis-adapter';
42+
import { createClient } from 'redis';
4743

4844
export class RedisIoAdapter extends IoAdapter {
45+
private adapterConstructor: ReturnType<typeof createAdapter>;
46+
47+
async connectToRedis(): Promise<void> {
48+
const pubClient = createClient({ url: `redis://localhost:6379` });
49+
const subClient = pubClient.duplicate();
50+
51+
await Promise.all([pubClient.connect(), subClient.connect()]);
52+
53+
this.adapterConstructor = createAdapter(pubClient, subClient);
54+
}
55+
4956
createIOServer(port: number, options?: ServerOptions): any {
5057
const server = super.createIOServer(port, options);
51-
server.adapter(redisAdapter);
58+
server.adapter(this.adapterConstructor);
5259
return server;
5360
}
5461
}
@@ -58,7 +65,11 @@ Afterward, simply switch to your newly created Redis adapter.
5865

5966
```typescript
6067
const app = await NestFactory.create(AppModule);
61-
app.useWebSocketAdapter(new RedisIoAdapter(app));
68+
const redisIoAdapter = new RedisIoAdapter(app);
69+
await redisIoAdapter.connectToRedis();
70+
71+
app.useWebSocketAdapter(redisIoAdapter);
72+
6273
```
6374

6475
#### Ws library

0 commit comments

Comments
 (0)