@graphql-mesh/serve-runtime
Version:
52 lines (51 loc) • 2 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useContentEncoding = useContentEncoding;
const server_1 = require("@whatwg-node/server");
function useContentEncoding({ subgraphs, }) {
if (!subgraphs?.length) {
return (0, server_1.useContentEncoding)();
}
const compressionAlgorithm = 'gzip';
let fetchAPI;
const execReqWithContentEncoding = new WeakSet();
return {
onYogaInit({ yoga }) {
fetchAPI = yoga.fetchAPI;
},
onPluginInit({ addPlugin }) {
addPlugin(
// @ts-expect-error - Typings are wrong
(0, server_1.useContentEncoding)());
},
onSubgraphExecute({ subgraphName, executionRequest }) {
if (subgraphs.includes(subgraphName)) {
execReqWithContentEncoding.add(executionRequest);
}
},
onFetch({ executionRequest, options, setOptions }) {
if (options.body &&
!options.headers?.['Content-Encoding'] &&
execReqWithContentEncoding.has(executionRequest)) {
const compressionStream = new fetchAPI.CompressionStream(compressionAlgorithm);
let bodyStream;
if (options.body instanceof fetchAPI.ReadableStream) {
bodyStream = options.body;
}
else {
// Create a fake Response and use its body to pipe through the compression stream
bodyStream = new fetchAPI.Response(options.body).body;
}
setOptions({
...options,
headers: {
'Accept-Encoding': 'gzip, deflate',
...options.headers,
'Content-Encoding': compressionAlgorithm,
},
body: bodyStream.pipeThrough(compressionStream),
});
}
},
};
}
;