Skip to content

Conversation

kwalski
Copy link

@kwalski kwalski commented Oct 10, 2018

Currently there is no way to pass on request derived context to fastify-graphql plugin's register call.

An example use case is when you have a Bearer jwt in request.headers.Authorization and you want to decode user info contained in it's payload and pass it on to graphql resolvers to query (or mutation) this user specific data.

graphQL api makes context available resolver functions' arguments (last argument)

Example usage:

const schema:`type Query{
                        hello (name:String) :String,
                 }`,
const resolvers: {
                        hello: (args, context)=>{
                        console.log(args, context) // args = name, context = { user:{ id:1, name:'John' } }
                        return 'hello '+args;
                    }
                 },

implement a function where you can access req, res . The function is supposed to returns GraphQLOptions object

 graphQLOptionsFn(req,res)=>{
    ... verify jwt and get payload from req.header.Authorization, e.g. `{ user:{ id:1, name:'John' } }` ...
   return {
                schema: schema,
                rootValue: resolvers,
                context:payload 
        }
 }); 

provide graphQLOptionsFn in plugin register call

  fastify.register(
        graphqlFastify,
         {
            prefix: "/graphql",
            graphql: graphQLOptionsFn
        },
        err => {
            if (err) {
                console.log(err);
                throw err;
            }
        }
    );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants