[nestjs] wss:// 설정

Edward Hyun·2022년 10월 21일
0

backend

목록 보기
109/120

main.js

async function bootstrap() {

    const privateKey = fs.readFileSync('certs/localhost.key', 'utf8');
    const certificate = fs.readFileSync('certs/localhost.cert', 'utf8');
    const httpsOptions = {key: privateKey, cert: certificate};

    const server = express();
    const app = await NestFactory.create(AppModule, new ExpressAdapter(server));

    const httpsServer = https.createServer(httpsOptions);
    app.useWebSocketAdapter(new ExtendedSocketIoAdapter(httpsServer));

    app.use(cookieParser());
    app.enableCors({
        origin: true,
        methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
        credentials: true,
    });

    await app.init();

    httpsServer.listen(3006);
}

ExtendedSocketIoAdapter.ts

import * as https from 'https';
import { IoAdapter } from '@nestjs/platform-socket.io';
import * as io from 'socket.io';

export class ExtendedSocketIoAdapter extends IoAdapter {
  protected ioServer: io.Server;

  constructor(protected server: https.Server) {
    super();

    const options = {
      cors: {
        origin: true,
        methods: ['GET', 'POST'],
        credentials: true,
      },
    };

    this.ioServer = new io.Server(server, options);
  }

  create(port: number) {
    console.log(
      'websocket gateway port argument is ignored by ExtendedSocketIoAdapter, use the same port of http instead',
    );
    return this.ioServer;
  }
}

단점 ::@WebSocketGateway({ namespace: 'videoChats' }) 여기서 namespace 같은 옵션이 무시된다. 같은 포트에 엔드포인트들이 동시에 연결된다.
wss://127.0.0.1:3000 으로 모든 namespace가 연결된다.

참고 )
https://stackoverflow.com/questions/70362938/nestjs-websocket-gateway-with-ssl-is-not-working
https://github.com/nestjs/nest/issues/126
https://stackoverflow.com/questions/57724813/nestjs-sets-both-http-and-https-servers/59084627#59084627

profile
앱&웹개발(flutter, vuejs, typescript, react), 인공지능(nlp, asr, rl), 백엔드(nodejs, flask, golang, grpc, webrtc, aws, msa, nft, spring cloud, nest.js), 함수형 프로그래밍(scala, erlang)을 공부하며 정리합니다.

0개의 댓글