@@ -37,21 +37,25 @@ Once the package is installed, we can create a `RedisIoAdapter` class.
3737
3838``` typescript
3939import { IoAdapter } from ' @nestjs/platform-socket.io' ;
40- import { Server , ServerOptions } from ' socket.io' ;
40+ import { ServerOptions } from ' socket.io' ;
4141import { createAdapter } from ' @socket.io/redis-adapter' ;
4242import { createClient } from ' redis' ;
4343
44- const io = new Server ();
45- const pubClient = createClient ({ url: ` redis://localhost:6379 ` });
46- const subClient = pubClient .duplicate ();
44+ export class RedisIoAdapter extends IoAdapter {
45+ private adapterConstructor: ReturnType <typeof createAdapter >;
4746
48- pubClient .connect ();
49- subClient .connect ();
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+ }
5055
51- export class RedisIoAdapter extends IoAdapter {
5256 createIOServer(port : number , options ? : ServerOptions ): any {
5357 const server = super .createIOServer (port , options );
54- server .adapter (createAdapter ( pubClient , subClient ) );
58+ server .adapter (this . adapterConstructor );
5559 return server ;
5660 }
5761}
@@ -61,7 +65,11 @@ Afterward, simply switch to your newly created Redis adapter.
6165
6266``` typescript
6367const app = await NestFactory .create (AppModule );
64- app .useWebSocketAdapter (new RedisIoAdapter (app ));
68+ const redisIoAdapter = new RedisIoAdapter (app );
69+ await redisIoAdapter .connectToRedis ();
70+
71+ app .useWebSocketAdapter (redisIoAdapter );
72+
6573```
6674
6775#### Ws library
0 commit comments