Created
December 8, 2020 18:58
-
-
Save crisu83/5f337218fc0b1b017ff6e7fefa3f8f63 to your computer and use it in GitHub Desktop.
GraphQL Next.js API route with `@graphql-tools` schema stitching
This file contains 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
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