Skip to content

Commit

Permalink
feat(installSubscriptionHandlers): enable passing WebSocket.Server in…
Browse files Browse the repository at this point in the history
…stead of HttpServer

For people who need to have multiple WebSocket servers sharing a single HTTP(S) server, the `ws` docs recommend [creating multiple instances of `new WebSocket.Server({ noServer: true })`](https://github.com/websockets/ws#multiple-servers-sharing-a-single-https-server).  This PR makes `installSubscriptionHandlers` accept a `WebSocket.Server` instance (in addition to accepting an http server) to support the multiple WebSocket servers use case.

Example:
```js
      const graphQLWebSocket = new WebSocket.Server({
        noServer: true,
      })
      apolloServer.installSubscriptionHandlers(graphQLWebSocket)

      const symmetryWebSocket = new WebSocket.Server({
        noServer: true,
      })
      symmetryWebSocket.on('connection', socket => new SymmetryServer({socket}))

      /**
       * This is a workaround.  When WebSocket.Server handles an upgrade request,
       * it will abort the handshake if the request path doesn't match -- meaning it
       * will break Meteor's DDP web socket.  So we only want the WebSocket.Server
       * for GraphQL to receive the upgrade event if it's not for Meteor.
       */
      httpServer.on('upgrade', (request: IncomingMessage, socket: net$Socket, head: any) => {
        if (request.url.startsWith(SYMMETRY_BROWSER_PATH)) {
          symmetryWebSocket.handleUpgrade(request, socket, head, (ws: WebSocket) => {
            symmetryWebSocket.emit('connection', ws)
          })
        } else if (request.url.startsWith(GRAPHQL_PATH)) {
          graphQLWebSocket.handleUpgrade(request, socket, head, (ws: WebSocket) => {
            graphQLWebSocket.emit('connection', ws)
          })
        } else {
          socket.destroy()
        }
      })
```
  • Loading branch information
jedwards1211 authored Feb 13, 2019
1 parent bb21951 commit cd9b0c5
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions packages/apollo-server-core/src/ApolloServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import {
ExecutionParams,
} from 'subscriptions-transport-ws';

import WebSocket from 'ws';

import { formatApolloErrors } from 'apollo-server-errors';
import {
GraphQLServerOptions as GraphQLOptions,
Expand Down Expand Up @@ -421,7 +423,7 @@ export class ApolloServerBase {
}
}

public installSubscriptionHandlers(server: HttpServer) {
public installSubscriptionHandlers(server: HttpServer | WebSocket.Server) {
if (!this.subscriptionServerOptions) {
if (this.supportsSubscriptions()) {
throw Error(
Expand Down Expand Up @@ -481,10 +483,12 @@ export class ApolloServerBase {
},
keepAlive,
},
{
server,
path,
},
server instanceof WebSocket.Server
? server
: {
server,
path,
}
);
}

Expand Down

0 comments on commit cd9b0c5

Please sign in to comment.