UNPKG

@nestjs/graphql

Version:

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

46 lines (45 loc) 1.83 kB
import { execute as graphqlExecute, subscribe as graphqlSubscribe, } from 'graphql'; import { GRAPHQL_TRANSPORT_WS_PROTOCOL, } from 'graphql-ws'; import { useServer } from 'graphql-ws/use/ws'; import { WebSocketServer } from 'ws'; export class GqlSubscriptionService { constructor(options, httpServer) { this.options = options; this.httpServer = httpServer; this.wss = new WebSocketServer({ path: this.options['graphql-ws']?.path ?? this.options.path, noServer: true, }); this.initialize(); } initialize() { const { execute = graphqlExecute, subscribe = graphqlSubscribe } = this.options; if ('graphql-ws' in this.options) { const graphqlWsOptions = this.options['graphql-ws'] === true ? {} : this.options['graphql-ws']; this.wsGqlDisposable = useServer({ schema: this.options.schema, execute, subscribe, context: this.options.context, ...graphqlWsOptions, }, this.wss); } this.httpServer.on('upgrade', (req, socket, head) => { const protocol = req.headers['sec-websocket-protocol']; let protocols = Array.isArray(protocol) ? protocol : protocol?.split(',').map((p) => p.trim()); protocols = protocols?.filter((supportedProtocol) => supportedProtocol === GRAPHQL_TRANSPORT_WS_PROTOCOL); const wss = this.wss; if (req.url?.startsWith(wss.options.path)) { wss.handleUpgrade(req, socket, head, (ws) => { wss.emit('connection', ws, req); }); } }); } async stop() { await this.wsGqlDisposable?.dispose(); } }