@graphql-mesh/http
Version:
79 lines (78 loc) • 3.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMeshHTTPHandler = void 0;
const cross_helpers_1 = require("@graphql-mesh/cross-helpers");
const utils_1 = require("@graphql-mesh/utils");
const router_1 = require("@whatwg-node/router");
const graphqlHandler_js_1 = require("./graphqlHandler.js");
function createMeshHTTPHandler({ baseDir, getBuiltMesh, rawServeConfig = {}, playgroundTitle, }) {
let readyFlag = false;
let logger = new utils_1.DefaultLogger('Mesh HTTP');
let mesh$;
const { cors: corsConfig, staticFiles, playground: playgroundEnabled, endpoint: graphqlPath = '/graphql',
// TODO
// trustProxy = 'loopback',
} = rawServeConfig;
const router = (0, router_1.createRouter)();
router.all('*', () => {
if (!mesh$) {
mesh$ = getBuiltMesh().then(mesh => {
readyFlag = true;
logger = mesh.logger.child('HTTP');
return mesh;
});
}
});
router.all('/healthcheck', () => new router_1.Response(null, {
status: 200,
}));
router.all('/readiness', () => new router_1.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 router_1.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 absolutePath = cross_helpers_1.path.join(baseDir, staticFiles, relativePath);
if (await (0, utils_1.pathExists)(absolutePath)) {
const readStream = cross_helpers_1.fs.createReadStream(absolutePath);
return new router_1.Response(readStream, {
status: 200,
});
}
return undefined;
});
}
else if (graphqlPath !== '/') {
router.get('/', () => new router_1.Response(null, {
status: 302,
headers: {
Location: graphqlPath,
},
}));
}
router.all('*', utils_1.withCookies);
router.all('*', (0, graphqlHandler_js_1.graphqlHandler)(() => mesh$, playgroundTitle, playgroundEnabled, graphqlPath, corsConfig));
return router;
}
exports.createMeshHTTPHandler = createMeshHTTPHandler;