@graphql-mesh/serve-runtime
Version:
52 lines (51 loc) • 2.09 kB
JavaScript
import { mapMaybePromise } from '@envelop/core';
import { subgraphNameByExecutionRequest } from '@graphql-mesh/fusion-runtime';
export 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 && subgraphNameByExecutionRequest.get(executionRequest);
let job;
if (opts.fromClientToSubgraphs) {
job = mapMaybePromise(opts.fromClientToSubgraphs({
request,
subgraphName,
}), headers => setOptions({
...options,
headers: {
...headers,
...options.headers,
},
}));
}
return mapMaybePromise(job, () => {
if (opts.fromSubgraphsToClient) {
return function onFetchDone({ response }) {
return 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);
}
}
}
},
};
}