@graphql-mesh/plugin-http2
Version:
67 lines (66 loc) • 2.45 kB
JavaScript
;
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 = (0, utils_1.createLruCache)();
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', () => {
sessionsByOrigin.keys().forEach(origin => {
const session = sessionsByOrigin.get(origin);
if (session) {
session.destroy();
}
});
});
return {
onFetch({ setFetchFn }) {
setFetchFn(function fetchForOrigin(url, options) {
const { origin, pathname, search } = new URL(url);
const session = getSessionByOrigin(origin);
const stream = session.request({
...(0, utils_1.getHeadersObj)(options.headers),
':method': options.method,
':path': pathname + 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;