Skip to content

Instantly share code, notes, and snippets.

@CrocoDillon
Last active October 27, 2021 20:42
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 CrocoDillon/0daba437631cae6f7b3db6490db03afc to your computer and use it in GitHub Desktop.
Save CrocoDillon/0daba437631cae6f7b3db6490db03afc to your computer and use it in GitHub Desktop.
POC ApolloServer for Next.js
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