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
In order to connect Fastify’s logger to the gateway, you need to install the
@graphql-hive/logger-pino
package together with @graphql-hive/gateway-runtime
and fastify
.
npm i @graphql-hive/gateway-runtime @graphql-hive/logger-pino fastify
import fastify, { type FastifyReply, type FastifyRequest } from 'fastify'
import { createGatewayRuntime } from '@graphql-hive/gateway-runtime'
import { createLoggerFromPino } from '@graphql-hive/logger-pino'
// Request ID header used for tracking requests
const requestIdHeader = 'x-request-id'
// This is the fastify instance you have created
const app = fastify({
logger: true,
// Use our custom request id header
requestIdHeader,
// Align with Hive Gateway's request id log label
requestIdLogLabel: 'requestId',
// Check the header first, then generate a new one if not found
genReqId: (req): string =>
req.headers[requestIdHeader]?.toString() || gw.fetchAPI.crypto.randomUUID()
})
// This will allow us to access Fastify request and reply objects in the gateway
interface FastifyContext {
req: FastifyRequest
reply: FastifyReply
}
const gateway = createGatewayRuntime<FastifyContext>({
// Integrate Fastify's logger / Pino with the gateway logger
logging: createLoggerFromPino(app.log),
// Align with Fastify
requestId: {
// Use the same header name as Fastify
headerName: requestIdHeader,
// Use the request id from Fastify (see `FastifyContext`)
generateRequestId: ({ context }) => context.req.id
},
// Point to the supergraph
supergraph: './supergraph.graphql'
})
// Bind the gateway to Fastify
app.route({
// "*" is recommendeded in order to handle landing page, readiness and other related endpoints
url: '*',
method: ['GET', 'POST', 'OPTIONS'],
// Connect the gateway to Fastify route
handler: (req, reply) => gateway.handleNodeRequestAndResponse(req, reply, { req, reply })
})
const port = 4000
app.listen({ port, host: '0.0.0.0' }, err => {
if (err) {
console.error('Error starting gateway', err)
process.exit(1)
}
console.log(`Gateway listening on port ${port}`)
})
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))
Last updated on