Skip to content

Instantly share code, notes, and snippets.

@owenallenaz
Last active March 19, 2019 16:52
Show Gist options
  • Save owenallenaz/d206464acae26c8612a63e0a69256e73 to your computer and use it in GitHub Desktop.
Save owenallenaz/d206464acae26c8612a63e0a69256e73 to your computer and use it in GitHub Desktop.
Using Apollo schema stitching with context and error handling
const { HttpLink } = require("apollo-link-http");
const { ApolloLink } = require("apollo-link");
const { setContext } = require("apollo-link-context");
const { onError } = require("apollo-link-error");
const fetch = require("node-fetch");
const express = require("express");
const { introspectSchema, makeRemoteExecutableSchema, ApolloServer, gql, mergeSchemas } = require("apollo-server-express");
const { TypeInfo, GraphQLSchema } = require("graphql");
const assert = require("assert");
const lodash = require("lodash");
const http = require("http");
const links = [
{
path : "http://someserver/"
},
{
path : "http://anotherserver/"
}
];
const schemas = [];
for(let link of links) {
// foreach link create an httplink
let remoteLink = new HttpLink({ uri : link.path, fetch });
let remoteContext = setContext((req, previous) => {
// if the authorization token doesn't exist, or is malformed, do not pass it upstream
if (
!previous.graphqlContext.authorization
||
!previous.graphqlContext.authorization.match(/^Bearer /)
) {
return;
}
return {
headers: {
'Authorization': previous.graphqlContext.authorization,
}
}
});
let remoteError = onError(({ networkError, graphQLErrors }) => {
if (graphQLErrors) {
graphQLErrors.forEach((val) => {
Object.setPrototypeOf(val, Error.prototype);
});
}
});
let remoteSchema = await introspectSchema(remoteLink);
let remoteExecutableSchema = makeRemoteExecutableSchema({
schema : remoteSchema,
link : ApolloLink.from([
remoteContext,
remoteError,
remoteLink
])
});
schemas.push(remoteExecutableSchema);
}
var schema = mergeSchemas({
schemas : schemas
});
const server = new ApolloServer({
schema,
context : ({ req }) => {
return {
authorization : req.headers.authorization
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment