@graphql-mesh/serve-runtime
Version:
55 lines (54 loc) • 2.25 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.usePropagateHeaders = usePropagateHeaders;
const core_1 = require("@envelop/core");
const fusion_runtime_1 = require("@graphql-mesh/fusion-runtime");
function usePropagateHeaders(opts) {
const resHeadersByRequest = new WeakMap();
return {
onFetch({ executionRequest, context, options, setOptions }) {
const request = context?.request || executionRequest?.context?.request;
if (request) {
const subgraphName = executionRequest && fusion_runtime_1.subgraphNameByExecutionRequest.get(executionRequest);
let job;
if (opts.fromClientToSubgraphs) {
job = (0, core_1.mapMaybePromise)(opts.fromClientToSubgraphs({
request,
subgraphName,
}), headers => setOptions({
...options,
headers: {
...headers,
...options.headers,
},
}));
}
return (0, core_1.mapMaybePromise)(job, () => {
if (opts.fromSubgraphsToClient) {
return function onFetchDone({ response }) {
return (0, core_1.mapMaybePromise)(opts.fromSubgraphsToClient({
response,
subgraphName,
}), headers => {
if (headers && request) {
resHeadersByRequest.set(request, headers);
}
});
};
}
});
}
},
onResponse({ response, request }) {
const headers = resHeadersByRequest.get(request);
if (headers) {
for (const key in headers) {
const value = headers[key];
if (value) {
response.headers.set(key, value);
}
}
}
},
};
}
;