UNPKG

@graphql-mesh/http

Version:
99 lines (98 loc) 4.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createMeshHTTPHandler = createMeshHTTPHandler; const cross_helpers_1 = require("@graphql-mesh/cross-helpers"); const utils_1 = require("@graphql-mesh/utils"); const server_1 = require("@whatwg-node/server"); const graphqlHandler_js_1 = require("./graphqlHandler.js"); function createMeshHTTPHandler({ baseDir, getBuiltMesh, rawServeConfig = {}, playgroundTitle, }) { let readyFlag = false; let logger = new utils_1.DefaultLogger('Mesh HTTP'); const { cors: corsConfig, staticFiles, playground: playgroundEnabled = cross_helpers_1.process.env.NODE_ENV !== 'production', endpoint: graphqlPath = '/graphql', batchingLimit, healthCheckEndpoint = '/healthcheck', // TODO // trustProxy = 'loopback', extraParamNames, } = rawServeConfig; getBuiltMesh() .then(mesh => { readyFlag = true; logger = mesh.logger.child('HTTP'); }) .catch(err => { logger.error(err); }); return (0, server_1.createServerAdapter)((0, graphqlHandler_js_1.graphqlHandler)({ getBuiltMesh, playgroundTitle, playgroundEnabled, graphqlEndpoint: graphqlPath, corsConfig, batchingLimit, extraParamNames, }), { plugins: [ { onRequest({ request, url, endResponse }) { switch (url.pathname) { case healthCheckEndpoint: endResponse(new server_1.Response(null, { status: 200, })); return; case '/readiness': endResponse(new server_1.Response(null, { status: readyFlag ? 204 : 503, })); return; } if (staticFiles && request.method === 'GET') { let relativePath = url.pathname; if (relativePath === '/' || !relativePath) { relativePath = 'index.html'; } const absoluteStaticFilesPath = cross_helpers_1.path.join(baseDir, staticFiles); const absolutePath = cross_helpers_1.path.join(absoluteStaticFilesPath, relativePath); if (absolutePath.startsWith(absoluteStaticFilesPath)) { return (0, utils_1.pathExists)(absolutePath).then(exists => { if (exists) { const readStream = cross_helpers_1.fs.createReadStream(absolutePath); endResponse(new server_1.Response(readStream, { status: 200, })); } }); } } else if (graphqlPath !== '/' && url.pathname === '/') { endResponse(new server_1.Response(null, { status: 302, headers: { Location: graphqlPath, }, })); // eslint-disable-next-line no-useless-return return; } (0, utils_1.withCookies)(request); if (readyFlag) { return getBuiltMesh().then(async (mesh) => { for (const eventName of mesh.pubsub.getEventNames()) { if (eventName === `webhook:${request.method.toLowerCase()}:${url.pathname}`) { const body = await request.text(); logger.debug(`Received webhook request for ${url.pathname}`, body); mesh.pubsub.publish(eventName, request.headers.get('content-type') === 'application/json' ? JSON.parse(body) : body); endResponse(new server_1.Response(null, { status: 204, statusText: 'OK', })); return; } } }); } }, }, ], }); }