UNPKG

@graphql-mesh/plugin-http2

Version:
68 lines (67 loc) 2.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /* eslint-disable import/no-nodejs-modules */ const http2_1 = require("http2"); const stream_1 = require("stream"); const utils_1 = require("@graphql-mesh/utils"); const fetch_1 = require("@whatwg-node/fetch"); function useHTTP2(opts) { const sessionsByOrigin = new Map(); function getSessionByOrigin(origin) { let session = sessionsByOrigin.get(origin); if (!session) { session = (0, http2_1.connect)(origin); sessionsByOrigin.set(origin, session); } return session; } opts.pubsub.subscribe('destroy', () => { for (const [, session] of sessionsByOrigin) { session.destroy(); } }); return { onFetch({ url, setFetchFn }) { const parsedUrl = new URL(url); const origin = parsedUrl.origin; if (opts.origins && !opts.origins.includes(origin)) { return; } setFetchFn(function fetchForOrigin(_url, options) { const session = getSessionByOrigin(origin); const stream = session.request({ ...(0, utils_1.getHeadersObj)(options.headers), ':method': options.method, ':path': parsedUrl.pathname + parsedUrl.search, }, { signal: options.signal, }); if (options.body) { stream_1.Readable.from(options.body).pipe(stream); } else { stream.end(); } return new Promise(resolve => { let status = 200; const responseHeaders = {}; stream.once('response', headers => { for (const key in headers) { if (key === ':status') { status = headers[key]; } else { responseHeaders[key] = headers[key]; } } resolve(new fetch_1.Response(stream, { headers: responseHeaders, status, })); }); }); }); }, }; } exports.default = useHTTP2;