fastify-graphql-ctx
TypeScript icon, indicating that this package has built-in type declarations

4.1.2 • Public • Published

fastify-graphql-ctx

Travis npm Conventional Commits

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
  }
);

Dependencies (3)

Dev Dependencies (19)

Package Sidebar

Install

npm i fastify-graphql-ctx

Weekly Downloads

1

Version

4.1.2

License

MIT

Unpacked Size

118 kB

Total Files

18

Last publish

Collaborators

  • kwalski