apollographql / apollo-link

:link: Interface for fetching and modifying control flow of GraphQL requests
https://www.apollographql.com/docs/link/
MIT License
1.44k stars 347 forks source link

Expose WS implementation options #1324

Open sekoyo opened 4 years ago

sekoyo commented 4 years ago

Hi, the subscriptions-transport-ws package has a 4th option:

constructor(
    url: string,
    options?: ClientOptions,
    webSocketImpl?: any,
    webSocketProtocols?: string | string[],
  )

Which is called here:

  private connect() {
    this.client = new this.wsImpl(this.url, this.wsProtocols);

This is an important option for using Apollo on Node since we typically use the ws package where the second parameter to ws is a bunch of important options.

One of these options is the ability to pass HTTP headers for example, which are not limited on the server. This makes it a lot simpler to implement secure subscriptions to other micro-services if the Apollo server is a gateway for example:

const wsLink = new ApolloLink((operation) => {
  const context = operation.getContext().graphqlContext

  const headers = {
    authorization: context.authToken,
  }

  // Create a new websocket link per request
  return new WebSocketLink({
    uri: subscriptionsUri,
    options: {
      reconnect: true,
      connectionParams: {
        headers,
      },
    },
    webSocketImpl: ws,
    webSocketImplOptions: { headers },
  }).request(operation)
})

Now we can forward secure subscriptions to other mircro-services as the upgrade request has an authorization header much more easily than waiting and parsing a connection_init message which contains connectionParams.

TODO:

apollo-cla commented 4 years ago

@DominicTobias: Thank you for submitting a pull request! Before we can merge it, you'll need to sign the Apollo Contributor License Agreement here: https://contribute.apollographql.com/