如何在type-graphql Resolver中读取ApolloServer的请求头
解决方法
你需要手动把请求头塞入ApolloServer返回的上下文对象中,再同步更新Context的TS类型定义,即可在resolver中直接调用,具体步骤如下:
1. 修改context构建逻辑
ApolloServer的context配置函数默认会接收请求元数据参数,以常用的Express集成场景为例,参数中包含req请求对象,你可以从中提取headers并加入返回的上下文对象中:
// src/context.ts import { PrismaClient } from '@prisma/client' import { IncomingHttpHeaders } from 'http' const prisma = new PrismaClient() // 更新Context接口定义,新增headers字段 export interface Context { prisma: PrismaClient headers: IncomingHttpHeaders } // 修改context返回值,把请求头塞进去 export const context = async ({ req }) => { return { prisma, headers: req.headers } }
2. 直接在resolver中调用
完成上述修改后,通过@Ctx()装饰器拿到的上下文对象就已经包含headers字段,可以直接使用:
@Query((returns) => Post, { nullable: true }) async postById(@Arg('id') id: number, @Ctx() ctx: Context) { // 打印所有请求头 console.log(ctx.headers) // 也可以取指定头,比如鉴权用的Authorization console.log(ctx.headers.authorization) return ctx.prisma.post.findUnique({ where: { id }, }) }
补充说明
你之前拿不到headers的原因是原示例的context函数仅返回了prisma实例,没有把请求相关的字段塞入上下文对象,type-graphql的@Ctx()装饰器获取到的内容,完全等价于你给ApolloServer配置的context函数的返回值,只要你把需要的字段加进去就能正常访问。
内容的提问来源于stack exchange,提问作者simj
相关产品推荐
相关产品推荐

