Created
September 4, 2021 09:40
-
-
Save crisu83/b6a2a93b29ee41de538fd33554e35aa4 to your computer and use it in GitHub Desktop.
GraphQL API route with remote schema
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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