首页 > 解决方案 > 使用 ApolloServer 从 type-graphql 解析器读取请求标头

问题描述

我正在按照这个示例使用 Prisma ORM、ApolloServer 和 type-graphql 来制作一个简单的博客 Web 应用程序。

我想检查 HTTP 请求标头,但无法确定如何在 type-graphql 解析器中访问 ApolloServer context.headers例如:

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

ApolloServer 在这里设置如下:

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

但是上面解析器中引用的@Ctx() ctx: Context只是 Prisma 上下文(在此处定义)而不是 ApolloServer 上下文。如果我记录 ctx 对象的密钥,我会得到:[ 'prisma', '_extensionStack' ]

在过去不使用 type-graphql 装饰器的 ApolloServer 项目中,我访问了 ApolloServer 上下文,如下所示:

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

如何从使用 type-graphql 装饰器的解析器访问请求标头?

标签: apollo-servertypegraphql

解决方案


推荐阅读