Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shanestillwell/fffb66698f6d046716cf623e9b7b693c to your computer and use it in GitHub Desktop.
Save shanestillwell/fffb66698f6d046716cf623e9b7b693c to your computer and use it in GitHub Desktop.
Apollo Gateway: Health Check: Schema Only
import { ApolloGateway } from "@apollo/gateway";
import { ApolloServer, gql } from "apollo-server-express";
const gateway = new ApolloGateway({ /* Options, maybe! */ });
const server = new ApolloServer({
subscriptions: false,
typeDefs: gql`
type Query {
book: String
}
`,
});
const HEALTH_CHECK_TIMEOUT_MILLIS = 2000;
server.applyMiddleware({
app,
path: '/',
// The Apollo Server `onHealthCheck` needs to be defined to enable
// functionality beyond merely returning "I'm okay!". This
// will check to see if there is a GraphQL schema ready to serve
// requests. It does not check for availability of downstream
// services.
onHealthCheck() {
// Timeout after 2 seconds.
let timerHandle;
const promiseOfTimeout = new Promise((resolve, reject) => {
timerHandle = setTimeout(
reject,
HEALTH_CHECK_TIMEOUT_MILLIS,
new Error('Health check timeout')
);
});
// The "{ __typename }" query only succeeds if there is a schema!
const promiseOfResult =
server.executeOperation({ query: "{ __typename }" })
.then((result) => {
// Check some criteria which validates execution at least started.
// In this case, presence of `data` and absence of `errors`.
// ... check more if you'd like!
if (!result ||
typeof result.data === 'undefined' ||
typeof result.errors !== 'undefined'
) {
console.error(result);
throw new Error("Unexpected error during health check!");
}
});
return Promise.race([promiseOfResult, promiseOfTimeout]);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment