Skip to content

Instantly share code, notes, and snippets.

@crisu83
Created September 4, 2021 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crisu83/b6a2a93b29ee41de538fd33554e35aa4 to your computer and use it in GitHub Desktop.
Save crisu83/b6a2a93b29ee41de538fd33554e35aa4 to your computer and use it in GitHub Desktop.
GraphQL API route with remote schema
// See: https://github.com/vercel/next.js/blob/canary/examples/api-routes-apollo-server/pages/api/graphql.js
import {AsyncExecutor} from '@graphql-tools/delegate';
import {introspectSchema, wrapSchema} from '@graphql-tools/wrap';
import {ApolloServer} from 'apollo-server-micro';
import {print} from 'graphql';
import fetch from 'isomorphic-unfetch';
import {NextApiRequest, NextApiResponse} from 'next';
import getConfig from 'next/config';
const {serverRuntimeConfig} = getConfig();
const createSchema = async () => {
const executor: AsyncExecutor = async ({document, variables}) => {
const query = print(document);
const result = await fetch(serverRuntimeConfig.githubEndpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({query, variables}),
});
return result.json();
};
return wrapSchema({
executor,
schema: await introspectSchema(executor),
});
};
export default async function graphql(
req: NextApiRequest,
res: NextApiResponse
) {
return new ApolloServer({
schema: await createSchema()
}).createHandler({path: '/api/graphql'})(req, res);
}
export const config = {
api: {
bodyParser: false,
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment