UNPKG

fuse

Version:

The magical GraphQL framework

109 lines (106 loc) 3.28 kB
// src/next/index.ts import { builder } from "fuse"; import { createYoga } from "graphql-yoga"; import { writeFile } from "fs/promises"; import { printSchema } from "graphql"; // src/utils/yoga-helpers.ts import { blockFieldSuggestionsPlugin } from "@escape.tech/graphql-armor-block-field-suggestions"; import { useDeferStream } from "@graphql-yoga/plugin-defer-stream"; import { useDisableIntrospection } from "@graphql-yoga/plugin-disable-introspection"; import { createStellateLoggerPlugin } from "stellate/graphql-yoga"; var getYogaPlugins = (stellate) => { return [ useDeferStream(), process.env.NODE_ENV === "production" && useDisableIntrospection(), process.env.NODE_ENV === "production" && blockFieldSuggestionsPlugin(), Boolean(process.env.NODE_ENV === "production" && stellate) && createStellateLoggerPlugin({ serviceName: stellate.serviceName, token: stellate.loggingToken, fetch }) ].filter(Boolean); }; var wrappedContext = (context) => { return async (ct) => { const baseContext = { request: ct.request, headers: ct.request.headers, params: ct.params }; if (typeof context === "function") { const userCtx = context(baseContext); if (userCtx.then) { const result = await userCtx; return { ...baseContext, ...result }; } return { ...baseContext, ...userCtx }; } else if (typeof context === "object") { return { ...baseContext, ...context }; } return baseContext; }; }; // src/next/index.ts var defaultQuery = ( /* GraphQL */ `query { _version } ` ); function createAPIRouteHandler(options) { return (request, context) => { const completedSchema = builder.toSchema({}); if (process.env.NODE_ENV === "development") { writeFile("./schema.graphql", printSchema(completedSchema), "utf-8"); } const { handleRequest } = createYoga({ maskedErrors: process.env.NODE_ENV === "production", graphiql: process.env.NODE_ENV !== "production" ? { title: "Fuse GraphiQL", defaultQuery } : false, schema: completedSchema, // We allow batching by default batching: true, context: wrappedContext(options?.context), // While using Next.js file convention for routing, we need to configure Yoga to use the correct endpoint graphqlEndpoint: "/api/fuse", // Yoga needs to know how to create a valid Next response fetchAPI: { Response }, plugins: getYogaPlugins(options?.stellate) }); return handleRequest(request, context); }; } function createPagesRouteHandler(options) { const schema = builder.toSchema({}); if (process.env.NODE_ENV === "development") { writeFile("./schema.graphql", printSchema(schema), "utf-8"); } return createYoga({ schema, graphiql: process.env.NODE_ENV !== "production" ? { title: "Fuse GraphiQL", defaultQuery } : false, maskedErrors: process.env.NODE_ENV === "production", batching: true, context: wrappedContext(options?.context), graphqlEndpoint: "/api/fuse", plugins: getYogaPlugins(options?.stellate) }); } export { createAPIRouteHandler, createPagesRouteHandler };