Reading request headers from type-graphql resolvers with ApolloServer

Viewed 553

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?

1 Answers

Please use the authorization API from Type-GQL to get the headers into the context and write business logic to further use them.

You can add as a function or a class level.

Example for function

export const customAuthChecker: AuthChecker<ContextType> = (
  { root, args, context, info },
  roles,
) => {
  // here we can read the user from context
  // and check his permission in the db against the `roles` argument
  // that comes from the `@Authorized` decorator, eg. ["ADMIN", "MODERATOR"]

  return true; // or false if access is denied
};

In the above ContextType is the object that you can create and use like a POJO etc.

Related