Search code examples
socket.iographqlnestjspublish-subscribesubscription

How to use socket.io with graphql subscription?


I want to make a real-time chat app by using nestjs and graphql technology. Most of tutorial uses PubSub but I don't know how to send a message to a specific client (?). I think it is much easy to use socket.io for sending a message to a specific client by using socket id.

this example using PubSub:

  1. Is there a way to send a message to a specific client by using PubSub? By reciving some data about sender like id.
  2. How can I replace PubSub with Socket.io ?I am really comfortable with socket.io

App.module.ts

import { Module, MiddlewareConsumer, RequestMethod, Get } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { typeOrmConfig } from './config/typeorm.config';
import { AuthModule } from './auth/auth.module';
import { LoggerMiddleware } from './common/middlewares/logger.middleware';
import { Connection } from 'typeorm';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
import { ChatModule } from './chat/chat.module';
import { ChatService } from './chat/chat.service';

@Module({
  imports: [
    TypeOrmModule.forRoot(typeOrmConfig), // connect to database
    GraphQLModule.forRoot({
      debug: true,
      playground: true,
      typePaths: ['**/*.graphql'],
      definitions: {
        path: join(process.cwd(), 'src/graphql.ts'),
      },
    }),
    AuthModule,
    ChatModule,
  ],
  controllers: [],
  providers: [
  ],
})
export class AppModule {
}

Chat.module.ts

import { Module } from '@nestjs/common';
import { ChatService } from './chat.service';
import { ChatResolver } from './chat.resolver';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from '../auth/auth.module';
import { PubSub } from 'graphql-subscriptions';

@Module({
  imports: [
    // Add all repository here; productRepository, ...
    TypeOrmModule.forFeature( [
      // repositories ...
    ]),
    AuthModule
  ],
  providers: [
     //=> How to replace with socket.io ?
     {
       provide: 'PUB_SUB',
       useValue: new PubSub(),
    },
    ChatService, 
    ChatResolver,
  ]
})
export class ChatModule {}

Chat.resolver.ts

import { Resolver, Query, Mutation, Args, Subscription } from '@nestjs/graphql';
import { PubSubEngine  } from 'graphql-subscriptions';
import { Inject } from '@nestjs/common';

const PONG_EVENT_NAME = 'pong';

@Resolver('Chat')
export class ChatResolver {
    constructor(
        private chatService: ChatService,

        @Inject('PUB_SUB') 
        private pubSub: PubSubEngine,
    ) {}

    // Ping Pong
    @Mutation('ping')
    async ping() {
        const pingId = Date.now();
        //=> How to send deta to specific client by using user-id?
        this.pubSub.publish(PONG_EVENT_NAME, { ['pong']: { pingId } });
        return { id: pingId };
    }

    @Subscription(PONG_EVENT_NAME)
    pong() {
        //=> how to get data about sender like id?
        return this.pubSub.asyncIterator(PONG_EVENT_NAME);
    }
}

Chat.graphql

type Mutation {
    ping: Ping
}

type Subscription {
  tagCreated: Tag
  clientCreated: Client
  pong: Pong
}

type Ping {
  id: ID
}

type Pong {
  pingId: ID
}

How can replace PubSub with Socket.io?


Solution

  • I didn't find any solution or example to get client-socket from graphql subscription. In most example they use Gateway instead of graphql pubsub. So I used GateWay to implement real-time activities and graphql for other request.