diff --git a/src/graphql/index.js b/src/graphql/index.js index 2df06f8dfb..2a9d324987 100644 --- a/src/graphql/index.js +++ b/src/graphql/index.js @@ -14,11 +14,9 @@ const errorHandler = require('./errorHandler'); const { access } = require('../auth/graphql/resolvers'); class GraphQL { - constructor(init, req, res) { + constructor(init) { Object.assign(this, init); this.init = this.init.bind(this); - this.req = req; - this.res = res; this.types = { blockTypes: {}, @@ -46,9 +44,7 @@ class GraphQL { this.buildPoliciesType = buildPoliciesType.bind(this); this.initCollections = initCollections.bind(this); this.initGlobals = initGlobals.bind(this); - } - init() { this.initCollections(); this.initGlobals(); @@ -69,34 +65,37 @@ class GraphQL { const query = new GraphQLObjectType(this.Query); const mutation = new GraphQLObjectType(this.Mutation); - const schema = new GraphQLSchema({ + + this.schema = new GraphQLSchema({ query, mutation, }); - let errorExtensions = []; - let errorExtensionIteration = 0; + this.errorExtensions = []; + this.errorExtensionIteration = 0; - const extensions = async (info) => { + this.extensions = async (info) => { const { result } = info; if (result.errors) { const afterErrorHook = typeof this.config.hooks.afterError === 'function' ? this.config.hooks.afterError : null; - errorExtensions = await errorHandler(info, this.config.debug, afterErrorHook); + this.errorExtensions = await errorHandler(info, this.config.debug, afterErrorHook); } return null; }; + } + init(req, res) { return graphQLHTTP({ - schema, + schema: this.schema, customFormatErrorFn: () => { const response = { - ...errorExtensions[errorExtensionIteration], + ...this.errorExtensions[this.errorExtensionIteration], }; - errorExtensionIteration += 1; + this.errorExtensionIteration += 1; return response; }, - extensions, - context: { req: this.req, res: this.res }, + extensions: this.extensions, + context: { req, res }, }); } } diff --git a/src/index.js b/src/index.js index 6b3dfdb50b..473f0f8b1a 100644 --- a/src/index.js +++ b/src/index.js @@ -55,10 +55,12 @@ class Payload { this.router.get('/access', access(this.config)); + const graphQLHandler = new GraphQL(this); + this.router.use( this.config.routes.graphQL, identifyAPI('GraphQL'), - (req, res) => new GraphQL(this, req, res).init()(req, res), + (req, res) => graphQLHandler.init(req, res)(req, res), ); this.router.get(this.config.routes.graphQLPlayground, graphQLPlayground({