UNPKG

2.54 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.SocketServerProvider = void 0;
4const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
5const server_and_event_streams_factory_1 = require("./factories/server-and-event-streams-factory");
6class SocketServerProvider {
7 constructor(socketsContainer, applicationConfig) {
8 this.socketsContainer = socketsContainer;
9 this.applicationConfig = applicationConfig;
10 }
11 scanForSocketServer(options, port) {
12 const serverAndStreamsHost = this.socketsContainer.getOneByConfig({
13 port,
14 path: options.path,
15 });
16 if (serverAndStreamsHost && options.namespace) {
17 return this.decorateWithNamespace(options, port, serverAndStreamsHost.server);
18 }
19 return serverAndStreamsHost
20 ? serverAndStreamsHost
21 : this.createSocketServer(options, port);
22 }
23 createSocketServer(options, port) {
24 const adapter = this.applicationConfig.getIoAdapter();
25 const { namespace, server, ...partialOptions } = options;
26 const ioServer = adapter.create(port, partialOptions);
27 const serverAndEventStreamsHost = server_and_event_streams_factory_1.ServerAndEventStreamsFactory.create(ioServer);
28 this.socketsContainer.addOne({ port, path: options.path }, serverAndEventStreamsHost);
29 if (!namespace) {
30 return serverAndEventStreamsHost;
31 }
32 return this.decorateWithNamespace(options, port, ioServer);
33 }
34 decorateWithNamespace(options, port, targetServer) {
35 const namespaceServer = this.getServerOfNamespace(options, port, targetServer);
36 const serverAndEventStreamsHost = server_and_event_streams_factory_1.ServerAndEventStreamsFactory.create(namespaceServer);
37 this.socketsContainer.addOne({ port, path: options.path, namespace: options.namespace }, serverAndEventStreamsHost);
38 return serverAndEventStreamsHost;
39 }
40 getServerOfNamespace(options, port, server) {
41 const adapter = this.applicationConfig.getIoAdapter();
42 return adapter.create(port, {
43 ...options,
44 namespace: this.validateNamespace(options.namespace || ''),
45 server,
46 });
47 }
48 validateNamespace(namespace) {
49 if (!(0, shared_utils_1.isString)(namespace)) {
50 return namespace;
51 }
52 return (0, shared_utils_1.addLeadingSlash)(namespace);
53 }
54}
55exports.SocketServerProvider = SocketServerProvider;