Skip to content

Instantly share code, notes, and snippets.

@timbophillips
Last active February 24, 2021 08:19
Show Gist options
  • Save timbophillips/37e56367ea6e30cdfd2058aff90750fe to your computer and use it in GitHub Desktop.
Save timbophillips/37e56367ea6e30cdfd2058aff90750fe to your computer and use it in GitHub Desktop.
import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import {
ApolloClientOptions,
InMemoryCache,
split,
ApolloLink,
} from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { OperationDefinitionNode } from 'graphql';
// Written by TJP based on https://apollo-angular.com/docs/data/subscriptions
// and then fixed up for updated TS and Apollo definitions
// Three options down the bottom
const httpURL = 'http://localhost:8080/v1/graphql'; // <-- add the URL of the GraphQL server here
const wsURL = 'ws://localhost:8080/v1/graphql';
// Standard HTTP
// tslint:disable-next-line: no-any
const createApolloHTTP = (httpLink: HttpLink): ApolloClientOptions<any> => ({
link: httpLink.create({ uri: httpURL }),
cache: new InMemoryCache(),
});
// Websockets
// tslint:disable-next-line: no-any
const createApolloWS = (httpLink: HttpLink): ApolloClientOptions<any> => ({
link: (new WebSocketLink({
uri: wsURL,
options: {
reconnect: true,
},
}) as unknown) as ApolloLink,
cache: new InMemoryCache(),
});
// Standard HTTP and WS depending on request
// tslint:disable-next-line: no-any
const createApolloBoth = (httpLink: HttpLink): ApolloClientOptions<any> => ({
link: split(
// split is a function from Apollo to alter the transport protocol based on operation type
// first argument does some disection of the query and returns a boolean,
// then the next two arguments return ApolloLink | RequestHandler objects
({ query }) => {
const { kind, operation } = getMainDefinition(
query
) as OperationDefinitionNode;
return kind === 'OperationDefinition' && operation === 'subscription';
},
new WebSocketLink({
uri: wsURL,
options: {
reconnect: true,
},
}),
httpLink.create({
uri: httpURL,
})
),
cache: new InMemoryCache(),
});
const apolloClientOptions = createApolloBoth; // <-- set this constant to one of createApolloHTTP, createApolloWS, or createApolloBoth
@NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: apolloClientOptions,
deps: [HttpLink],
},
],
})
export class GraphQLModule {}