Skip to content

Commit

Permalink
apollo-server-core: pass req obj to context when invoking executeOper…
Browse files Browse the repository at this point in the history
…ation

Fixes apollographql#2277.

`apollo-server-testing` relies on `apollo-server-core` to execute queries
for integration tests, via the `executeOperation` method.

However, when executing a query via `executeOperation`, `apollo-server-core`
was not passing the `req` object to the `context` callback function used
to create the server.

This is fine if you're using a mock `context` object directly in
your tests, but for tests that want to run a `context` callback that
contains logic that depends on that `req` object, it would fail.

Note that long-term the best fix for this is that `apollo-server-testing`
should use the `ApolloServer` class from `apollo-server-express` internally,
instead of `ApolloServerBase` from `apollo-server-core`, since it seems
like that is the class that is used by default in `apollo-server`.
  • Loading branch information
vitorbal committed Mar 21, 2019
1 parent 8850e0f commit c28fb31
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,8 @@

### vNEXT

- `apollo-server-core`: Pass request object to `context` callback function when invoking the `executeOperation` method.

### v2.4.3

- `apollo-server-lambda`: Fix typings which triggered "Module has no default export" errors. [PR #2230](https://github.com/apollographql/apollo-server/pull/2230)
Expand Down
2 changes: 1 addition & 1 deletion packages/apollo-server-core/src/ApolloServer.ts
Expand Up @@ -565,7 +565,7 @@ export class ApolloServerBase {
let options;

try {
options = await this.graphQLServerOptions();
options = await this.graphQLServerOptions({ req: request });
} catch (e) {
e.message = `Invalid options provided to ApolloServer: ${e.message}`;
throw new Error(e);
Expand Down
40 changes: 40 additions & 0 deletions packages/apollo-server-core/src/__tests__/ApolloServer.test.ts
@@ -0,0 +1,40 @@
import MockReq = require('mock-req');

import { ApolloServerBase } from '../ApolloServer';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';

const queryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
testString: {
type: GraphQLString,
resolve() {
return 'it works';
},
},
},
});

describe('ApolloServer', () => {
describe('executeOperation', () => {
it('Passes the request object to the context callback', () => {
const schema = new GraphQLSchema({
query: queryType,
});
const contextMock = jest.fn();
const apolloServer = new ApolloServerBase({
schema,
context: contextMock,
});
const mockRequest = new MockReq();
const operation = {
query: '{ }',
http: mockRequest,
};

apolloServer.executeOperation(operation);

expect(contextMock).toHaveBeenCalledWith({ req: operation });
});
});
});

0 comments on commit c28fb31

Please sign in to comment.