Skip to content

Instantly share code, notes, and snippets.

@eladchen
Created July 10, 2020 07:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eladchen/00251cfd96a3fc4fe0c986d83fd48bc2 to your computer and use it in GitHub Desktop.
Save eladchen/00251cfd96a3fc4fe0c986d83fd48bc2 to your computer and use it in GitHub Desktop.
An example of how to access apollo context in formatError() method.
import { Request, Response } from "express";
import { GraphQLError, GraphQLFormattedError } from "graphql";
import { GraphQLServerOptions } from "apollo-server-core/src/graphqlOptions";
import { ApolloServer, ApolloServerExpressConfig as C } from "apollo-server-express";
export type FormatError = (graphQLError: GraphQLError, context: unknown) => GraphQLFormattedError;
export type ApolloServerExpressConfig = Omit<C, "formatError"> & {
formatError?: FormatError;
};
/**
* A modified instance of apollo express server class
* that calls formatError() method with the context value.
*/
export class CustomApolloServer extends ApolloServer {
constructor(config: ApolloServerExpressConfig) {
super(config as C);
}
async createGraphQLServerOptions(req: Request, res: Response): Promise<GraphQLServerOptions> {
const options = await super.createGraphQLServerOptions(req, res);
if (typeof options.formatError === "function") {
const formatError = options.formatError as FormatError;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
options.formatError = (graphQLError: GraphQLError) => {
return formatError(graphQLError, options.context);
};
}
return options;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment