Skip to content

Instantly share code, notes, and snippets.

@sean-brydon
Created November 22, 2021 11:38
Show Gist options
  • Save sean-brydon/cbec2e55ae3e759002b6c84123bb8606 to your computer and use it in GitHub Desktop.
Save sean-brydon/cbec2e55ae3e759002b6c84123bb8606 to your computer and use it in GitHub Desktop.
import { schema } from '~/graphql/index';
import { Context, createGraphQLContext } from '~/graphql/builder';
import {
getGraphQLParameters,
processRequest,
renderGraphiQL,
shouldRenderGraphiQL,
} from 'graphql-helix';
import { NextApiHandler } from 'next';
import { ExecutionResult, GraphQLError } from 'graphql';
import { IncomingHttpHeaders } from 'http';
import { resolveSession } from '~/utils/sessions';
const handler: NextApiHandler = async (req, res) => {
const session = await resolveSession({ req, res });
try {
const request: GraphQLRequest = {
headers: req.headers,
method: req.method ?? 'GET',
query: req.query,
body: req.body,
};
if (shouldRenderGraphiQL(request)) {
res.setHeader('Content-Type', 'text/html');
res.send(
renderGraphiQL({
endpoint: '/api/graphql',
headers: JSON.stringify({
'X-CSRF-Trick': 'Charity',
}),
}),
);
} else {
const { operationName, query, variables } = getGraphQLParameters(request);
const result = await processRequest<Context>({
operationName,
query,
variables,
request,
schema,
contextFactory: () => createGraphQLContext(req, res, session),
});
if (result.type !== 'RESPONSE') {
throw new Error(`Unsupported response type: "${result.type}"`);
}
result.headers.forEach(({ name, value }) => res.setHeader(name, value));
res.status(result.status);
res.json(formatResult(result.payload));
}
} catch (err) {
res.status(500);
res.end(String(err));
}
};
export default handler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment