From 3bec29065fabe5c5b8edad6e7bb5fc2660075155 Mon Sep 17 00:00:00 2001 From: Eric Wyne Date: Thu, 11 Jan 2018 14:07:59 -0800 Subject: [PATCH] feat: export a `prepare` function (#72) Using `prepare` allows for building a `GraphQLOptions` object that is _not_ a callback. --- src/gramps.js | 18 +++++++++++++++--- src/index.js | 1 + test/gramps.test.js | 13 ++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/gramps.js b/src/gramps.js index cf293e7..2fc59e8 100644 --- a/src/gramps.js +++ b/src/gramps.js @@ -100,7 +100,7 @@ const mapSourcesToExecutableSchemas = (sources, shouldMock, options) => * @param {Object?} config.apollo options for Apollo functions * @return {Function} req => options for `graphqlExpress()` */ -export default function gramps({ +export function prepare({ dataSources = [], enableMockData = process.env.GRAMPS_MODE === 'mock', extraContext = req => ({}), // eslint-disable-line no-unused-vars @@ -150,10 +150,22 @@ export default function gramps({ }, extra); }; - return req => ({ + return { schema, - context: getContext(req), + context: getContext, + addContext: (req, res, next) => { + req.gramps = getContext(req); + next(); + }, // formatError: formatError(logger), ...apolloOptions.graphqlExpress, + }; +} + +export default function gramps(...args) { + const options = prepare(...args); + return req => ({ + ...options, + context: options.context(req), }); } diff --git a/src/index.js b/src/index.js index 6e66ed8..3b26bda 100644 --- a/src/index.js +++ b/src/index.js @@ -1,3 +1,4 @@ import gramps from './gramps'; +export { prepare } from './gramps'; export default gramps; diff --git a/test/gramps.test.js b/test/gramps.test.js index 9a548ec..11d4168 100644 --- a/test/gramps.test.js +++ b/test/gramps.test.js @@ -1,12 +1,23 @@ import { GraphQLSchema } from 'graphql'; import * as GraphQLTools from 'graphql-tools'; -import gramps from '../src'; +import gramps, { prepare } from '../src'; describe('GrAMPS', () => { beforeEach(() => { jest.clearAllMocks(); }); + describe('prepare()', () => { + it('addContext() adds gramps property to request object', () => { + const { addContext } = prepare(); + const next = jest.genMockFn(); + const req = {}; + addContext(req, {}, next); + expect(req).toEqual({ gramps: {} }); + expect(next).toBeCalled(); + }); + }); + describe('gramps()', () => { it('creates a valid schema and empty context with no arguments', () => { const getGrampsContext = gramps();