fastify-graphql-ctx
v4.1.2
Published
Apollo server plugin for Fastify
Downloads
5
Readme
fastify-graphql-ctx
A plugin for Fastify that adds GraphQL and GraphiQL support.
This project was forked from fastify-graphql it provides additional middelware capabilities by allowing you access to fastify request and response to pass context to your graphql queries or mutations. See Context for resolvers example below
Installation
npm install --save fastify-graphql-ctx graphql
Usage
const Fastify = require('fastify');
const app = Fastify();
const {graphiqlFastify, graphqlFastify} = require('fastify-graphql-ctx');
app.register(graphqlFastify, {
prefix: '/graphql',
graphql: {
schema: your_graphql_schema,
},
});
app.register(graphiqlFastify, {
prefix: '/graphiql',
graphiql: {
endpointURL: '/graphql',
}
});
Configuration
Both plugins need to be given a prefix, under which they will mount.
GraphQL settings extends GraphQLServerOptions
GraphiQL settings extends GraphiQLData
Context for resolvers
If you want to pass a request context to resolvers like following (eg: parse request header Bearer tokens to identify who has called the query)
const schema:`type Query{
hello (name:String) :String,
}`,
const resolvers: {
hello: (args, context)=>{
console.log(args, context)
// args = name from query call; context = { user:{ id:1, name:'John' } }
return 'hello '+args;
}
},
then implement a function to access fastify's req, res. The function will be called before graphQL and must returns GraphQLOptions object like following
graphQLOptionsFn(req,res)=>{
let payload = { user:{ id:1, name:'John' } }; //parsed from req.headers...
return {
schema: schema,
rootValue: resolvers,
context: payload
}
});
provide graphQLOptionsFn in plugin register call. It will be executed synchronously to ensure execution before graphQL API
fastify.register(graphqlFastify, {
prefix: "/graphql",
graphql: graphQLOptionsFn
}
);