Skip to content

Commit 2f6b55d

Browse files
Merge pull request #2662 from Davide-Gheri/fix/apollo-context
Fix/apollo context
2 parents 03fc641 + 291d5c5 commit 2f6b55d

File tree

4 files changed

+103
-7
lines changed

4 files changed

+103
-7
lines changed

packages/apollo/lib/drivers/apollo-base.driver.ts

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,12 @@ export abstract class ApolloBaseDriver<
133133

134134
await server.start();
135135

136-
app.use(path, expressMiddleware(server));
136+
app.use(
137+
path,
138+
expressMiddleware(server, {
139+
context: options.context,
140+
}),
141+
);
137142

138143
this.apolloServer = server;
139144
}
@@ -171,7 +176,9 @@ export abstract class ApolloBaseDriver<
171176
app.route({
172177
url: path,
173178
method: ['GET', 'POST', 'OPTIONS'],
174-
handler: fastifyApolloHandler(server),
179+
handler: fastifyApolloHandler(server, {
180+
context: options.context,
181+
}),
175182
});
176183

177184
this.apolloServer = server;
@@ -231,18 +238,26 @@ export abstract class ApolloBaseDriver<
231238
originalOptions: ApolloDriverConfig = { ...targetOptions },
232239
) {
233240
if (!targetOptions.context) {
234-
targetOptions.context = ({ req, request }) => ({ req: req ?? request });
241+
targetOptions.context = async (contextOrRequest) => {
242+
return {
243+
// New ApolloServer fastify integration has Request as first parameter to the Context function
244+
req: contextOrRequest.req ?? contextOrRequest,
245+
};
246+
};
235247
} else if (isFunction(targetOptions.context)) {
236248
targetOptions.context = async (...args: unknown[]) => {
237249
const ctx = await (originalOptions.context as Function)(...args);
238-
const { req, request } = args[0] as Record<string, unknown>;
239-
return this.assignReqProperty(ctx, req ?? request);
250+
const contextOrRequest = args[0] as Record<string, unknown>;
251+
return this.assignReqProperty(
252+
ctx,
253+
contextOrRequest.req ?? contextOrRequest,
254+
);
240255
};
241256
} else {
242-
targetOptions.context = ({ req, request }: Record<string, unknown>) => {
257+
targetOptions.context = async (contextOrRequest) => {
243258
return this.assignReqProperty(
244259
originalOptions.context as Record<string, any>,
245-
req ?? request,
260+
contextOrRequest.req ?? contextOrRequest,
246261
);
247262
};
248263
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { INestApplication } from '@nestjs/common';
2+
import { ExpressAdapter } from '@nestjs/platform-express';
3+
import { Test } from '@nestjs/testing';
4+
import * as request from 'supertest';
5+
import { CustomContextModule } from '../graphql/custom-context/custom-context.module';
6+
import { FastifyAdapter } from '@nestjs/platform-fastify';
7+
8+
describe('GraphQL (custom context)', () => {
9+
let app: INestApplication;
10+
11+
describe.each([
12+
['Express', new ExpressAdapter()],
13+
['Fastify', new FastifyAdapter()],
14+
])('Custom context with %s', (_, adapter) => {
15+
beforeEach(async () => {
16+
const module = await Test.createTestingModule({
17+
imports: [CustomContextModule],
18+
}).compile();
19+
20+
app = module.createNestApplication(adapter);
21+
await app.init();
22+
23+
const instance = app.getHttpAdapter().getInstance();
24+
if ('ready' in instance && typeof instance.ready === 'function') {
25+
await instance.ready();
26+
}
27+
});
28+
29+
it('should return query result', () => {
30+
return request(app.getHttpServer())
31+
.post('/graphql')
32+
.send({
33+
operationName: null,
34+
variables: {},
35+
query: `
36+
{
37+
fooFromContext
38+
}
39+
`,
40+
})
41+
.expect(200, {
42+
data: {
43+
fooFromContext: 'bar',
44+
},
45+
});
46+
});
47+
48+
afterEach(async () => {
49+
await app.close();
50+
});
51+
});
52+
});
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Module } from '@nestjs/common';
2+
import { GraphQLModule } from '@nestjs/graphql';
3+
import { ApolloDriverConfig } from '../../../lib';
4+
import { ApolloDriver } from '../../../lib/drivers';
5+
import { CustomContextResolver } from './custom-context.resolver';
6+
7+
@Module({
8+
imports: [
9+
GraphQLModule.forRoot<ApolloDriverConfig>({
10+
driver: ApolloDriver,
11+
autoSchemaFile: true,
12+
context: (request) => ({
13+
foo: 'bar',
14+
request,
15+
}),
16+
}),
17+
],
18+
providers: [CustomContextResolver],
19+
})
20+
export class CustomContextModule {}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { Resolver, Query, Context } from '@nestjs/graphql';
2+
3+
@Resolver()
4+
export class CustomContextResolver {
5+
@Query(() => String)
6+
fooFromContext(@Context() ctx: Record<string, unknown>) {
7+
return ctx.foo;
8+
}
9+
}

0 commit comments

Comments
 (0)