apollo-servertypegraphql

Reading request headers from type-graphql resolvers with ApolloServer


I am following this example that uses Prisma ORM, ApolloServer and type-graphql to make a simple blog web app.

I want to inspect the HTTP request headers and I'm having trouble working out how to access the ApolloServer context.headers in a type-graphql resolver such as this:

  @Query((returns) => Post, { nullable: true })
  async postById(@Arg('id') id: number, @Ctx() ctx: Context) {
    return ctx.prisma.post.findUnique({
      where: { id },
    })
  }

The ApolloServer is set up here like this:

new ApolloServer({ schema, context: context }).listen({ port: 4000 }, () =>
    console.log(`Server ready at: http://localhost:4000`), )

But the @Ctx() ctx: Context referenced in the resolver above is only the Prisma context (defined here) not the ApolloServer context. If I log the keys for the ctx object I get: [ 'prisma', '_extensionStack' ]

In past ApolloServer projects that do not use type-graphql decorators I have accessed the ApolloServer context like this:

postById: async (_, { id }, apolloServerContext) => {... console.log(apolloServerContext.headers)

How can I access the request headers from the resolver that uses type-graphql decorators?


Solution

  • You can use IncomingMessage as the type of the context object in the Resolver query.

    But first, you need to pass context parameter to ApolloServer's constructor like the following:

    new ApolloServer({
      schema: schema,
      context: ({ req }) => {
        return req;
      },
     });
    

    Then you will be able to consume it in the Resolver like this:

    import { Ctx, Query, Resolver } from "type-graphql";
    import { IncomingMessage } from "http";
    
    @Resolver()
    export class TestResolver {
      constructor(private readonly service: TestService) {}
    
      @Query(() => Data, { nullable: true })
      async getDataForUser(@Ctx() context: IncomingMessage): Promise<Data> {
        const headers = context.headers;
        return await this.service.fetchData();
      }
    }