Last active
October 27, 2021 20:42
-
-
Save CrocoDillon/0daba437631cae6f7b3db6490db03afc to your computer and use it in GitHub Desktop.
POC ApolloServer for Next.js
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 { | |
ApolloServerBase, | |
convertNodeHttpToRequest, | |
isHttpQueryError, | |
runHttpQuery, | |
} from 'apollo-server-core' | |
import { parseBody } from 'next/dist/server/api-utils' | |
const setHeaders = (res, headers) => { | |
Object.entries(headers).forEach(([header, value]) => { | |
res.setHeader(header, value) | |
}) | |
} | |
class ApolloServer extends ApolloServerBase { | |
serverlessFramework() { | |
return true | |
} | |
createHandler() { | |
return async (req, res) => { | |
await this.ensureStarted() | |
const landingPage = this.getLandingPage() | |
try { | |
if ( | |
landingPage && | |
req.method === 'GET' && | |
req.headers['accept'].includes('text/html') | |
) { | |
res.setHeader('Content-Type', 'text/html; charset=utf-8') | |
res.status(200).send(landingPage.html) | |
return | |
} | |
let filePayload | |
if (req.headers['content-type']?.startsWith('multipart/form-data')) { | |
let processRequest | |
try { | |
processRequest = require('graphql-upload').processRequest | |
} catch (e) { | |
throw new Error( | |
'To use uploads install the package `graphql-upload`' | |
) | |
} | |
filePayload = await processRequest(req, res) | |
} | |
const query = | |
req.method === 'POST' | |
? filePayload || | |
(req.headers['content-type'] === 'application/json' && | |
req.headers['content-length'] && | |
req.headers['content-length'] !== '0' && | |
(await parseBody(req, '1mb'))) | |
: req.query | |
const { graphqlResponse, responseInit } = await runHttpQuery( | |
[req, res], | |
{ | |
method: req.method, | |
options: this.graphQLServerOptions({ req, res }), | |
query, | |
request: convertNodeHttpToRequest(req), | |
} | |
) | |
setHeaders(res, responseInit.headers) | |
res.status(responseInit.status || 200).json(graphqlResponse) | |
} catch (e) { | |
if (isHttpQueryError(e) && e.headers) { | |
setHeaders(res, e.headers) | |
} | |
res.status(e.statusCode || e.status || 500).send(e.message) | |
} | |
} | |
} | |
} | |
export default ApolloServer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment