Created
July 10, 2020 07:06
-
-
Save eladchen/00251cfd96a3fc4fe0c986d83fd48bc2 to your computer and use it in GitHub Desktop.
An example of how to access apollo context in formatError() method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Hi @eladchen ,
I think you could consider about the
didEncounterErrors
event which fires when Apollo Server encounters errors while parsing, validating, or executing a GraphQL operation. The errors are available on requestContext.errors.E.g.