From 7591429c3e8cd0fb6078be0c533394a0cc5a511d Mon Sep 17 00:00:00 2001 From: Jonas Helfer Date: Mon, 4 Jul 2016 22:51:13 -0700 Subject: [PATCH] add try/catch and test for rejected options --- src/integrations/expressApollo.test.ts | 16 ++++++++++++++++ src/integrations/expressApollo.ts | 7 ++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/integrations/expressApollo.test.ts b/src/integrations/expressApollo.test.ts index b1a8e694892..ca87c62bfdb 100644 --- a/src/integrations/expressApollo.test.ts +++ b/src/integrations/expressApollo.test.ts @@ -67,6 +67,22 @@ describe('expressApollo', () => { expect(() => graphqlHTTP(undefined as ExpressApolloOptions)).to.throw('Apollo Server requires options.'); }); + it('throws an error if options promise is rejected', () => { + const app = express(); + app.use('/graphql', bodyParser.json()); + app.use('/graphql', graphqlHTTP( (req) => (Promise.reject({})) as any as ExpressApolloOptions)); + const expected = 'Invalid options'; + const req = request(app) + .post('/graphql') + .send({ + query: 'query test{ testString }', + }); + return req.then((res) => { + expect(res.status).to.equal(500); + return expect(res.error.text).to.contain(expected); + }); + }); + it('can be called with an options function', () => { const app = express(); app.use('/graphql', bodyParser.json()); diff --git a/src/integrations/expressApollo.ts b/src/integrations/expressApollo.ts index 970333e7fe0..4f4a8d9faee 100644 --- a/src/integrations/expressApollo.ts +++ b/src/integrations/expressApollo.ts @@ -55,7 +55,12 @@ export function graphqlHTTP(options: ExpressApolloOptions | ExpressApolloOptions return async (req: express.Request, res: express.Response, next) => { let optionsObject: ExpressApolloOptions; if (isOptionsFunction(options)) { - optionsObject = await options(req); + try { + optionsObject = await options(req); + } catch (e) { + res.status(500); + res.send(`Invalid options provided to ApolloServer: ${e.message}`); + } } else { optionsObject = options; }