Integration with Fastify

Fastify is one of the popular HTTP server frameworks for Node.js. It is a very simple, yet powerful framework that is easy to learn and use.

You can easily integrate Hive Gateway with Fastify.

So you can benefit from the powerful plugins of Fastify ecosystem with Hive Gateway. See the ecosystem

Example

import fastify, { FastifyReply, FastifyRequest } from 'fastify'
import { createGatewayRuntime } from '@graphql-hive/gateway'
 
// This is the fastify instance you have created
const app = fastify({ logger: true })
 
const serveRuntime = createGatewayRuntime<{
  req: FastifyRequest
  reply: FastifyReply
}>({
  // Integrate Fastify logger
  logging: {
    debug: (...args) => args.forEach(arg => app.log.debug(arg)),
    info: (...args) => args.forEach(arg => app.log.info(arg)),
    warn: (...args) => args.forEach(arg => app.log.warn(arg)),
    error: (...args) => args.forEach(arg => app.log.error(arg))
  }
})
 
/**
 * We pass the incoming HTTP request to Hive Gateway
 * and handle the response using Fastify's `reply` API
 * Learn more about `reply` https://www.fastify.io/docs/latest/Reply/
 **/
app.route({
  // Bind to the Hive Gateway's endpoint to avoid rendering on any path
  url: serveRuntime.graphqlEndpoint,
  method: ['GET', 'POST', 'OPTIONS'],
  handler: async (req, reply) => {
    // Second parameter adds Fastify's `req` and `reply` to the GraphQL Context
    const response = await serveRuntime.handleNodeRequestAndResponse(req, reply, {
      req,
      reply
    })
    response.headers.forEach((value, key) => {
      reply.header(key, value)
    })
 
    reply.status(response.status)
 
    reply.send(response.body)
 
    return reply
  }
})
 
app.listen(4000)

Add dummy content type parser for File Uploads

Fastify needs to be aware of Hive Gateway will handle multipart/form-data requests because otherwise it will throw an error something like Unsupported media type.

// This will allow Fastify to forward multipart requests to Hive Gateway
app.addContentTypeParser('multipart/form-data', {}, (req, payload, done) => done(null))