Last active
October 4, 2021 13:09
-
-
Save ziedHamdi/a2ee15beda91dc4e5f56c69e0538646e to your computer and use it in GitHub Desktop.
Next.js pages/api/ graphql endpoint
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 logger from '../../lib/logger' | |
import {getSession} from "next-auth/client"; | |
import dynamic from "next/dynamic"; | |
function isTrueStr(str) { | |
return str === true || | |
(str != null && | |
str.toString().toLowerCase() === 'true') | |
} | |
/** | |
* typeof window == 'undefined' doesn't work here, so client HttpLink was enriched by a header boolean field 'ssr' | |
* @param req | |
* @returns {Promise<{"content-type": string, "infra-token": *}>} | |
*/ | |
async function prepareHeaders(req) { | |
let infraToken = "" | |
const ssr = isTrueStr(req.headers['ssr']) | |
if (ssr == true) { | |
//in SSR, we rely on client.query({context:{headers:{'infra-token':token}}}) | |
infraToken = req.headers['infra-token'] | |
} else { | |
//in client rendering, we rely on the user that made the request | |
const session = await getSession({req}) | |
infraToken = session?.infraToken | |
} | |
// logger.debug("api/graphql: {ssr: ", ssr, " Request token:", infraToken) | |
let headers = { | |
'content-type': 'application/json', | |
'infra-token': infraToken, | |
ssr | |
} | |
//On server-side, we must wrap our headers in a node-fetch Header class instance | |
if (ssr) { | |
const Headers = (await import('node-fetch')).Headers | |
headers = new Headers(headers) | |
} | |
return headers; | |
} | |
export default async (_req, _res) => { | |
let headers = await prepareHeaders(_req); | |
const query = { | |
method: 'POST', // *GET, POST, PUT, DELETE, etc. | |
mode: 'cors', // no-cors, *cors, same-origin | |
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached | |
headers, | |
redirect: 'follow', // manual, *follow, error | |
body: JSON.stringify({ | |
operationName: _req.body.operationName, | |
variables: _req.body.variables, | |
query: _req.body.query | |
}) // body data type must match "Content-Type" header | |
}; | |
const graphqlBaseUrl = process.env.NEXT_PUBLIC_BACK_END_URL | |
const res = await fetch(graphqlBaseUrl + '/api/graphql', query) | |
const json = await res.json() | |
_res.statusCode = 200; | |
_res.setHeader('content-type', 'application/json'); | |
_res.setHeader('cache-control', 'no-store, max-age=0'); | |
_res.json(json) | |
_res.end() | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment