0

I needed to grab the authentication header and pass it along on my fetch. 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.

So the question is how does someone get a header value within your query/mutations??

Vince
  • 757
  • 1
  • 8
  • 16
  • just read docs? https://www.apollographql.com/docs/apollo-server/security/authentication/#putting-authenticated-user-info-on-the-context – xadm Mar 24 '21 at 16:32
  • I found how to access context and how to use it in graphql with a text schema, but I could not find one ounce of documentation explaining that @Ctx was how I query the context values. – Vince Mar 25 '21 at 02:26

1 Answers1

0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Vince
  • 757
  • 1
  • 8
  • 16