@@ -37,21 +37,25 @@ Once the package is installed, we can create a `RedisIoAdapter` class.
37
37
38
38
``` typescript
39
39
import { IoAdapter } from ' @nestjs/platform-socket.io' ;
40
- import { Server , ServerOptions } from ' socket.io' ;
40
+ import { ServerOptions } from ' socket.io' ;
41
41
import { createAdapter } from ' @socket.io/redis-adapter' ;
42
42
import { createClient } from ' redis' ;
43
43
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 >;
47
46
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
+ }
50
55
51
- export class RedisIoAdapter extends IoAdapter {
52
56
createIOServer(port : number , options ? : ServerOptions ): any {
53
57
const server = super .createIOServer (port , options );
54
- server .adapter (createAdapter ( pubClient , subClient ) );
58
+ server .adapter (this . adapterConstructor );
55
59
return server ;
56
60
}
57
61
}
@@ -61,7 +65,11 @@ Afterward, simply switch to your newly created Redis adapter.
61
65
62
66
``` typescript
63
67
const 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
+
65
73
```
66
74
67
75
#### Ws library
0 commit comments