简体   繁体   English

如何使用生成的模式获取 GraphQL 请求上下文

[英]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.

相关问题 覆盖 GraphQL Schema 生成的 Typescript 类型 - Override from GraphQL Schema generated Typescript types 如何从 GraphQL 模式生成 GraphQL 操作 - How to generate GraphQL operations from GraphQL schema 如何使用 react 和 typescript 将类型添加到 graphql 模式? - How to add type to graphql schema using react and typescript? GraphQL:如何在不使用 graphql-type-json 的情况下处理混合了 String 和 JSON 的模式? - GraphQL: How to handle a schema with a mix of String and JSON without using graphql-type-json? 如何在没有操作的情况下使用 graphql schema.json 为 graphql 类型生成打字稿接口? - How to generate typescript interfaces for graphql types using a graphql schema.json without operations? ExpressJS + TypeScript如何获取请求上下文 - ExpressJS+TypeScript How to get a request context Laravel Lighthouse:如何让 graphql-codegen 从我的模式生成类型? - Laravel Lighthouse: How can I get graphql-codegen to generate typings from my schema? 如何在 GraphQL 中创建通用的分页连接模式 - How to create a generic Pagination Connections schema in GraphQL 如果我不使用放大,如何从 AppSync GraphQL 架构生成 Typescript 定义? - How to generate Typescript definitions from AppSync GraphQL schema if I am not using amplify? 在将 aws cdk 与 appsync 一起使用时,如何将突变添加到 graphql 架构并防止部署失败? - While using aws cdk with appsync, how to add mutation to graphql schema and prevent deployment from failing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM