1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.GqlSubscriptionService = void 0;
|
4 | const graphql_1 = require("graphql");
|
5 | const graphql_ws_1 = require("graphql-ws");
|
6 | const ws_1 = require("graphql-ws/lib/use/ws");
|
7 | const subscriptions_transport_ws_1 = require("subscriptions-transport-ws");
|
8 | const ws = require("ws");
|
9 | class GqlSubscriptionService {
|
10 | constructor(options, httpServer) {
|
11 | this.options = options;
|
12 | this.httpServer = httpServer;
|
13 | this.wss = new ws.Server({
|
14 | path: this.options['graphql-ws']?.path ??
|
15 | this.options.path,
|
16 | noServer: true,
|
17 | });
|
18 | this.subTransWs = new ws.Server({
|
19 | path: this.options['subscriptions-transport-ws']?.path ?? this.options.path,
|
20 | noServer: true,
|
21 | });
|
22 | this.initialize();
|
23 | }
|
24 | initialize() {
|
25 | const supportedProtocols = [];
|
26 | const { execute = graphql_1.execute, subscribe = graphql_1.subscribe } = this.options;
|
27 | if ('graphql-ws' in this.options) {
|
28 | const graphqlWsOptions = this.options['graphql-ws'] === true ? {} : this.options['graphql-ws'];
|
29 | supportedProtocols.push(graphql_ws_1.GRAPHQL_TRANSPORT_WS_PROTOCOL);
|
30 | this.wsGqlDisposable = (0, ws_1.useServer)({
|
31 | schema: this.options.schema,
|
32 | execute,
|
33 | subscribe,
|
34 | context: this.options.context,
|
35 | ...graphqlWsOptions,
|
36 | }, this.wss);
|
37 | }
|
38 | if ('subscriptions-transport-ws' in this.options) {
|
39 | const subscriptionsWsOptions = this.options['subscriptions-transport-ws'] === true
|
40 | ? {}
|
41 | : this.options['subscriptions-transport-ws'];
|
42 | supportedProtocols.push(subscriptions_transport_ws_1.GRAPHQL_WS);
|
43 | this.subServer = subscriptions_transport_ws_1.SubscriptionServer.create({
|
44 | schema: this.options.schema,
|
45 | execute,
|
46 | subscribe,
|
47 | ...subscriptionsWsOptions,
|
48 | }, this.subTransWs);
|
49 | }
|
50 | this.httpServer.on('upgrade', (req, socket, head) => {
|
51 | const protocol = req.headers['sec-websocket-protocol'];
|
52 | let protocols = Array.isArray(protocol)
|
53 | ? protocol
|
54 | : protocol?.split(',').map((p) => p.trim());
|
55 | protocols = protocols?.filter((protocol) => supportedProtocols.includes(protocol));
|
56 | const wss = protocols?.includes(subscriptions_transport_ws_1.GRAPHQL_WS) &&
|
57 | !protocols.includes(graphql_ws_1.GRAPHQL_TRANSPORT_WS_PROTOCOL)
|
58 | ? this.subTransWs
|
59 | : this.wss;
|
60 | if (req.url?.startsWith(wss.options.path)) {
|
61 | wss.handleUpgrade(req, socket, head, (ws) => {
|
62 | wss.emit('connection', ws, req);
|
63 | });
|
64 | }
|
65 | });
|
66 | }
|
67 | async stop() {
|
68 | await this.wsGqlDisposable?.dispose();
|
69 | this.subServer?.close();
|
70 | }
|
71 | }
|
72 | exports.GqlSubscriptionService = GqlSubscriptionService;
|