UNPKG

@graphql-mesh/serve-runtime

Version:
49 lines (48 loc) 1.9 kB
import { useContentEncoding as useOrigContentEncoding } from '@whatwg-node/server'; export function useContentEncoding({ subgraphs, }) { if (!subgraphs?.length) { return useOrigContentEncoding(); } const compressionAlgorithm = 'gzip'; let fetchAPI; const execReqWithContentEncoding = new WeakSet(); return { onYogaInit({ yoga }) { fetchAPI = yoga.fetchAPI; }, onPluginInit({ addPlugin }) { addPlugin( // @ts-expect-error - Typings are wrong useOrigContentEncoding()); }, 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), }); } }, }; }