Skip to content

Commit

Permalink
feat: websocket to use redis
Browse files Browse the repository at this point in the history
  • Loading branch information
rubiin committed Jan 14, 2023
1 parent 51037ac commit 26959b3
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 16 deletions.
27 changes: 15 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
"description": "NestJS + MikroORM blog example with batteries included",
"license": "MIT",
"author": {
"name": "Rubin Bhandari",
"email": "roobin.bhandari@gmail.com",
"url": "https://rubiin.ml"
},
"name": "Rubin Bhandari",
"email": "roobin.bhandari@gmail.com",
"url": "https://rubiin.ml"
},
"repository": "https://github.com/rubiin/ultimate-nest",
"homepage": "https://github.com/rubiin/ultimate-nest#readme",
"bugs": "https://github.com/rubiin/ultimate-nest/issues",
Expand All @@ -28,10 +28,10 @@
"jest",
"casl",
"nestjs-boilerplate",
"nestjs-mikroorm",
"nestjs-starter-template",
"nestjs-template"
],
"nestjs-mikroorm",
"nestjs-starter-template",
"nestjs-template"
],
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
Expand Down Expand Up @@ -78,6 +78,7 @@
"@sentry/hub": "^7.30.0",
"@sentry/node": "^7.30.0",
"@sentry/types": "^7.30.0",
"@socket.io/redis-adapter": "^8.0.1",
"@supercharge/request-ip": "^1.2.0",
"argon2": "^0.30.3",
"cache-manager": "5.1.4",
Expand Down Expand Up @@ -110,9 +111,11 @@
"preview-email": "^3.0.7",
"prom-client": "^14.1.1",
"pug": "^3.0.2",
"redis": "^4.5.1",
"reflect-metadata": "0.1.13",
"rxjs": "^7.8.0",
"sharp": "^0.31.3",
"socket.io": "^4.5.4",
"swagger-stats": "^0.99.5",
"twilio": "3.84.1",
"unprofane": "^1.0.3",
Expand Down Expand Up @@ -222,8 +225,8 @@
}
},
"pnpm": {
"overrides": {
"jsonwebtoken": "^9.0.0"
}
}
"overrides": {
"jsonwebtoken": "^9.0.0"
}
}
}
43 changes: 43 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,15 @@ const bootstrap = async () => {

app.useGlobalFilters(new I18nValidationExceptionFilter({ detailedErrors: false }));
app.setGlobalPrefix(globalPrefix);
app.useWebSocketAdapter(new SocketIOAdapter(app));

// =========================================================
// configureWebSocket
// =========================================================

const redisIoAdapter = new SocketIOAdapter(app, configService);

await redisIoAdapter.connectToRedis();
app.useWebSocketAdapter(redisIoAdapter);

// =========================================================
// configureNestSwagger
Expand Down
6 changes: 6 additions & 0 deletions src/modules/chat/chat.gateway.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Logger } from "@nestjs/common";
import {
ConnectedSocket,
MessageBody,
Expand All @@ -15,9 +16,14 @@ import { CreateChatDto } from "./dto/create-chat.dto";
})
export class ChatGateway {
@WebSocketServer() server: Namespace;
private readonly logger = new Logger(ChatGateway.name);

constructor(private readonly chatService: ChatService) {}

afterInit(): void {
this.logger.log(`💬 Websocket Gateway initialized.`);
}

@SubscribeMessage("createChat")
async create(@MessageBody() createChatDto: CreateChatDto, @ConnectedSocket() client: Socket) {
const message = this.chatService.create(createChatDto, client.id);
Expand Down
21 changes: 18 additions & 3 deletions src/socket-io.adapter.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
import { INestApplicationContext, Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { IoAdapter } from "@nestjs/platform-socket.io";
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";
import { Server, ServerOptions } from "socket.io";

export class SocketIOAdapter extends IoAdapter {
private readonly logger = new Logger(SocketIOAdapter.name);
private adapterConstructor: ReturnType<typeof createAdapter>;

constructor(private app: INestApplicationContext) {
constructor(private app: INestApplicationContext, private readonly config: ConfigService) {
super(app);
}

async connectToRedis(): Promise<void> {
const pubClient = createClient({ url: this.config.get("redis.uri") });
const subClient = pubClient.duplicate();

await Promise.all([pubClient.connect(), subClient.connect()]);

this.adapterConstructor = createAdapter(pubClient, subClient);
}

createIOServer(port: number, options?: ServerOptions) {
const _clientPort = 8000;
const clientUrl = this.config.get("app.clientUrl");

const cors = {
origin: [`http://localhost:${_clientPort}`],
origin: [clientUrl],
};

const optionsWithCORS: ServerOptions = {
Expand All @@ -23,6 +36,8 @@ export class SocketIOAdapter extends IoAdapter {

const server: Server = super.createIOServer(port, optionsWithCORS);

server.adapter(this.adapterConstructor);

return server;
}
}

0 comments on commit 26959b3

Please sign in to comment.