UNPKG

@nestjs/websockets

Version:

Nest - modern, fast, powerful node.js web framework (@websockets)

54 lines (53 loc) 2.31 kB
import { ServerAndEventStreamsFactory } from './factories/server-and-event-streams-factory.js'; import { addLeadingSlash, isString } from '@nestjs/common/internal'; export class SocketServerProvider { socketsContainer; applicationConfig; constructor(socketsContainer, applicationConfig) { this.socketsContainer = socketsContainer; this.applicationConfig = applicationConfig; } scanForSocketServer(options, port) { const serverAndStreamsHost = this.socketsContainer.getOneByConfig({ port, path: options.path, }); if (serverAndStreamsHost && options.namespace) { return this.decorateWithNamespace(options, port, serverAndStreamsHost.server); } return serverAndStreamsHost ? serverAndStreamsHost : this.createSocketServer(options, port); } createSocketServer(options, port) { const adapter = this.applicationConfig.getIoAdapter(); const { namespace, server, ...partialOptions } = options; const ioServer = adapter.create(port, partialOptions); const serverAndEventStreamsHost = ServerAndEventStreamsFactory.create(ioServer); this.socketsContainer.addOne({ port, path: options.path }, serverAndEventStreamsHost); if (!namespace) { return serverAndEventStreamsHost; } return this.decorateWithNamespace(options, port, ioServer); } decorateWithNamespace(options, port, targetServer) { const namespaceServer = this.getServerOfNamespace(options, port, targetServer); const serverAndEventStreamsHost = ServerAndEventStreamsFactory.create(namespaceServer); this.socketsContainer.addOne({ port, path: options.path, namespace: options.namespace }, serverAndEventStreamsHost); return serverAndEventStreamsHost; } getServerOfNamespace(options, port, server) { const adapter = this.applicationConfig.getIoAdapter(); return adapter.create(port, { ...options, namespace: this.validateNamespace(options.namespace || ''), server, }); } validateNamespace(namespace) { if (!isString(namespace)) { return namespace; } return addLeadingSlash(namespace); } }