skip to Main Content

First of all, sorry for grammar mistakes, English is not my native language.

I just wanted to use Redis with NestJS and created an adapter for it. It would be more appropriate if I said I got the code from NestJS’s own examples directly. Here is my Redis client:

import Redis from "ioredis";
import { CONFIG } from "src/config";

export const redis = new Redis(CONFIG.REDIS_URL);

And this is the adapter:

import { IoAdapter } from "@nestjs/platform-socket.io";
import { createAdapter } from "socket.io-redis";
import { redis } from "./redis";
import { ServerOptions } from "socket.io";

export class RedisIoAdapter extends IoAdapter {
    createIOServer(port: number, options?: ServerOptions): any {
        const server = super.createIOServer(port, options);
        const pubClient = redis;
        const subClient = redis.duplicate();
        const redisAdapter = createAdapter({
            pubClient,
            subClient,
        });
        server.adapter(redisAdapter);
        return server;
    }
}

But when I try to use it on my application it says

app.useWebSocketAdapter(new RedisIoAdapter(app));
Argument of type 'RedisIoAdapter' is not assignable to parameter of type 'WebSocketAdapter<any, any, any>'. Type 'RedisIoAdapter' is missing the following properties from type 'WebSocketAdapter<any, any, any>': bindClientConnect, close

Thanks for all of your helps :3

2

Answers


  1. One issue could be because of not installing @nestjs/websockets.
    Please make sure you have installed @nestjs/websockets npm package.

    Login or Signup to reply.
  2. Here is how i have defined RedisIoAdapter class.

    import { RedisClient } from 'redis';
    import { ServerOptions } from 'socket.io';
    import { createAdapter } from 'socket.io-redis';
    import { IoAdapter } from '@nestjs/platform-socket.io';
    
    const pubClient = new RedisClient({
      host: process.env.REDIS_HOST,
      port: process.env.REDIS_PORT
    });
    const subClient = pubClient.duplicate();
    const redisAdapter = createAdapter({ pubClient, subClient });
    
    export class RedisIoAdapter extends IoAdapter {
      createIOServer(port: number, options?: ServerOptions): any {
        const server = super.createIOServer(port, options);
        server.adapter(redisAdapter);
        return server;
      }
    }

    And in main.ts I have included following way:

    import { RedisIoAdapter } from './common/redis-adapter';
    
    ...
    async function bootstrap() {
       const app = await NestFactory.create<NestExpressApplication>(AppModule);
       // Uses Redis Adapter
       app.useWebSocketAdapter(new 
       RedisIoAdapter((<any>app).getHttpServer()));
       ...
    }
    
    // Starting App now
    bootstrap();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search