bun add @graphql-hive/gateway-runtime @graphql-hive/logger fastify
import fastify, { type FastifyReply, type FastifyRequest } from "fastify";import { createGatewayRuntime, Logger } from "@graphql-hive/gateway-runtime";import { PinoLogWriter } from "@graphql-hive/logger/writers/pino";// Request ID header used for tracking requestsconst requestIdHeader = "x-request-id";// This is the fastify instance you have createdconst 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 gatewayinterface FastifyContext { req: FastifyRequest; reply: FastifyReply;}const gateway = createGatewayRuntime<FastifyContext>({ // Use Fastify's logger (Pino) with Hive Logger logging: new Logger({ writers: [new PinoLogWriter(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 Fastifyapp.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 Gatewayapp.addContentTypeParser("multipart/form-data", {}, (req, payload, done) => done(null),);
This site uses cookies for analytics and improving your experience.