@nestjs/graphql
Version:
GraphQL for NestJS: code-first and schema-first APIs, resolvers as providers, subscriptions, federation and generated SDL, on Apollo or Mercurius.
85 lines (84 loc) • 4.01 kB
JavaScript
import { execute as graphqlExecute, subscribe as graphqlSubscribe, } from 'graphql';
import { useServer } from 'graphql-ws/use/ws';
import { WebSocketServer } from 'ws';
const DEFAULT_UNCLAIMED_UPGRADE_TIMEOUT = 1000;
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, unclaimedUpgradeTimeout = DEFAULT_UNCLAIMED_UPGRADE_TIMEOUT, ...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();
}
else if (unclaimedUpgradeTimeout > 0) {
// A listener that claims the socket answers the handshake, so a socket
// nothing has been written to by then is one that nobody claimed. The
// HTTP server's timeouts no longer apply after "upgrade", so it would
// otherwise stay open until the client hangs up. The count covers the
// whole connection, so on a keep-alive connection it already includes
// the responses to earlier requests.
const writtenBeforeUpgrade = socket.bytesWritten;
setTimeout(() => {
if (socket.writable && socket.bytesWritten <= writtenBeforeUpgrade) {
socket.destroy();
}
}, unclaimedUpgradeTimeout).unref();
}
});
}
async stop() {
await this.wsGqlDisposable?.dispose();
}
}