UNPKG

@graphql-mesh/http

Version:
76 lines (75 loc) 3.02 kB
import { fs, path } from '@graphql-mesh/cross-helpers'; import { DefaultLogger, pathExists, withCookies } from '@graphql-mesh/utils'; import { createRouter, Response } from '@whatwg-node/router'; import { graphqlHandler } from './graphqlHandler.js'; export function createMeshHTTPHandler({ baseDir, getBuiltMesh, rawServeConfig = {}, playgroundTitle, }) { let readyFlag = false; let logger = new DefaultLogger('Mesh HTTP'); let mesh$; const { cors: corsConfig, staticFiles, playground: playgroundEnabled, endpoint: graphqlPath = '/graphql', // TODO // trustProxy = 'loopback', } = rawServeConfig; const router = createRouter(); router.all('*', () => { if (!mesh$) { mesh$ = getBuiltMesh().then(mesh => { readyFlag = true; logger = mesh.logger.child('HTTP'); return mesh; }); } }); router.all('/healthcheck', () => new Response(null, { status: 200, })); router.all('/readiness', () => new Response(null, { status: readyFlag ? 204 : 503, })); router.post('*', async (request) => { if (readyFlag) { const { pubsub } = await mesh$; for (const eventName of pubsub.getEventNames()) { const { pathname } = new URL(request.url); if (eventName === `webhook:${request.method.toLowerCase()}:${pathname}`) { const body = await request.text(); logger.debug(`Received webhook request for ${pathname}`, body); pubsub.publish(eventName, request.headers.get('content-type') === 'application/json' ? JSON.parse(body) : body); return new Response(null, { status: 204, statusText: 'OK', }); } } } return undefined; }); if (staticFiles) { router.get('/:relativePath+', async (request) => { let { relativePath } = request.params; if (!relativePath) { relativePath = 'index.html'; } const absoluteStaticFilesPath = path.join(baseDir, staticFiles); const absolutePath = path.join(absoluteStaticFilesPath, relativePath); if (absolutePath.startsWith(absoluteStaticFilesPath) && (await pathExists(absolutePath))) { const readStream = fs.createReadStream(absolutePath); return new Response(readStream, { status: 200, }); } return undefined; }); } else if (graphqlPath !== '/') { router.get('/', () => new Response(null, { status: 302, headers: { Location: graphqlPath, }, })); } router.all('*', withCookies); router.all('*', graphqlHandler(() => mesh$, playgroundTitle, playgroundEnabled, graphqlPath, corsConfig)); return router; }