[英]How to get GraphQL request context using generated schema
I needed to grab the authentication header and pass it along on my fetch.我需要获取身份验证 header 并将其传递给我的获取。 I found a few different ways to do it but wanted access to the context so I can grab it.
我找到了几种不同的方法来做到这一点,但想要访问上下文以便我可以抓住它。 All the documentation I saw wasn't related to the typescript way of generating the schema.
我看到的所有文档都与生成模式的 typescript 方式无关。
So the question is how does someone get a header value within your query/mutations??所以问题是有人如何在您的查询/突变中获得 header 值?
So I never found the answer online but decided I should post this in case someone else runs into this issue.所以我从来没有在网上找到答案,但决定我应该发布这个,以防其他人遇到这个问题。
First you need to setup the context that'll be used首先,您需要设置将要使用的上下文
const schema = await buildSchema({
resolvers: [
YourResolver
]
});
const apolloServer = new ApolloServer({
schema,
context: ({ req }) => {
// this will return something you can pick up using @Ctx("param")
const someValue: string = req.headers["some-value"] as string;
var obj = {
value: someValue
};
return obj;
}
});
Second you need to reference it其次,您需要参考它
@Query(() => string, { nullable: true })
async Get (
@Ctx("value") val: string
): Promise<string> {
return new Promise<string>((res:any) => { res(value); });
}
Works in Query, Mutations, and FieldResolvers.适用于查询、突变和字段解析器。 No param should return the whole object, haven't tested it.
没有参数应该返回整个 object,没有测试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.