Skip to content

Instantly share code, notes, and snippets.

@enriquebrgn
Created November 6, 2018 16:54
Show Gist options
  • Save enriquebrgn/b3d6557f86472c48ae62f82f85e0dc8e to your computer and use it in GitHub Desktop.
Save enriquebrgn/b3d6557f86472c48ae62f82f85e0dc8e to your computer and use it in GitHub Desktop.
Secure subscription stitching
import { from } from 'apollo-link'
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { split } from 'apollo-client-preset'
import { hasSubscription } from "@jumpn/utils-graphql";
import SocketLink from './socketLink';
import fetch from 'node-fetch';
import { introspectSchema, makeRemoteExecutableSchema } from 'graphql-tools';
import { GraphQLSchema } from "graphql";
export const getRemoteSchema = async (uri, subUri: string): Promise<GraphQLSchema> => {
const httpLink = new HttpLink({ uri, fetch });
const wsLink = new SocketLink(subUri)
const contextLink = setContext((_, previousContext) => ({
headers: {
authorization: previousContext.graphqlContext.request.headers.authorization
}
}));
const wsContextLink = setContext((_, previousContext) => {
wsLink.watchChanges(previousContext.graphqlContext.connection.context.Authorization)
});
const link = split(
operation => hasSubscription(operation.query),
from([wsContextLink, wsLink]),
from([contextLink, httpLink]),
);
const schema = await introspectSchema(httpLink);
const executableSchema = makeRemoteExecutableSchema({
schema,
link,
});
return executableSchema;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment