UNPKG

@nestjs/graphql

Version:

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

70 lines (69 loc) • 3.03 kB
import { execute as graphqlExecute, subscribe as graphqlSubscribe, } from 'graphql'; import { useServer } from 'graphql-ws/use/ws'; import { WebSocketServer } from 'ws'; export class GqlSubscriptionService { constructor(options, httpServer) { this.options = options; this.httpServer = httpServer; const graphqlWsConfig = typeof this.options['graphql-ws'] === 'object' ? this.options['graphql-ws'] : undefined; const customServer = graphqlWsConfig?.server; if (customServer && !customServer.options?.noServer) { throw new Error('Custom WebSocketServer passed to "graphql-ws" must be instantiated with "noServer: true".'); } this.path = customServer?.options.path ?? graphqlWsConfig?.path ?? this.options.path; this.wss = customServer ?? new WebSocketServer({ path: this.path, noServer: true, }); this.initialize(); } initialize() { const { execute = graphqlExecute, subscribe = graphqlSubscribe } = this.options; const graphqlWsConfig = this.options['graphql-ws']; if (!graphqlWsConfig) { // No protocol handler would listen on the WebSocket server: leave upgrade // requests to the HTTP server rather than completing handshakes on // sockets that nothing reads from. return; } const { server: _wsServer, path: _wsPath, ...graphqlWsOptions } = graphqlWsConfig === true ? {} : graphqlWsConfig; this.wsGqlDisposable = useServer({ schema: this.options.schema, execute, subscribe, context: this.options.context, ...graphqlWsOptions, }, this.wss); this.httpServer.on('upgrade', (req, socket, head) => { // Match the whole path, as "WebSocketServer#shouldHandle()" does: a // prefix match would also claim requests that another upgrade listener // owns, and a socket handed to two servers crashes the process. const pathname = req.url?.split('?', 1)[0]; if (this.path && pathname === this.path) { const wss = this.wss; wss.handleUpgrade(req, socket, head, (ws) => { wss.emit('connection', ws, req); }); return; } // Node.js detaches its own listeners from the socket before emitting // "upgrade", so a socket that nobody claims has no "error" listener and // a connection reset would crash the process. When no other listener // can claim it, close it right away. socket.on('error', () => socket.destroy()); if (this.httpServer.listenerCount('upgrade') <= 1) { socket.destroy(); } }); } async stop() { await this.wsGqlDisposable?.dispose(); } }