Skip to content

Instantly share code, notes, and snippets.

@crisu83

crisu83/graphql.ts

Created Dec 8, 2020
Embed
What would you like to do?
GraphQL Next.js API route with `@graphql-tools` schema stitching
import {isProduction} from '@/utils';
import {Executor} from '@graphql-tools/delegate';
import {makeExecutableSchema} from '@graphql-tools/schema';
import {stitchSchemas} from '@graphql-tools/stitch';
import {introspectSchema, wrapSchema} from '@graphql-tools/wrap';
import {graphqlHTTP} from 'express-graphql';
import {GraphQLSchema, print} from 'graphql';
import fetch from 'isomorphic-unfetch';
import {NextApiRequest, NextApiResponse} from 'next';
import getConfig from 'next/config';
const {serverRuntimeConfig} = getConfig();
export const config = {
api: {
bodyParser: false,
},
};
const createLocalSchema = () =>
makeExecutableSchema({
resolvers: {
Query: {
hello: () => 'Hello from Next.js!',
},
},
typeDefs: `
type Query {
hello: String!
}
`,
});
const createDgraphSchema = async () => {
const executor: Executor = async ({document, variables}) => {
const query = print(document);
const result = await fetch(serverRuntimeConfig.dgraphEndpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({query, variables}),
});
return result.json();
};
return wrapSchema({
executor,
schema: await introspectSchema(executor as any),
});
};
let schemaGateway: GraphQLSchema;
const getSchemaGateway = async () => {
if (!schemaGateway) {
schemaGateway = stitchSchemas({
subschemas: [
{schema: createLocalSchema()},
{schema: await createDgraphSchema()},
],
});
}
return schemaGateway;
};
const createHandler = async () =>
graphqlHTTP({
graphiql: !isProduction,
schema: await getSchemaGateway(),
});
export default async function graphql(
req: NextApiRequest,
res: NextApiResponse
) {
return (await createHandler())(req as any, res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment