@graphql-mesh/supergraph
Version:
80 lines (79 loc) • 3.3 kB
JavaScript
import { parse } from 'graphql';
import { process } from '@graphql-mesh/cross-helpers';
import { PredefinedProxyOptions } from '@graphql-mesh/store';
import { getInterpolatedHeadersFactory, stringInterpolator, } from '@graphql-mesh/string-interpolation';
import { isUrl, readFile, readUrl } from '@graphql-mesh/utils';
import { buildHTTPExecutor } from '@graphql-tools/executor-http';
import { getStitchedSchemaFromSupergraphSdl } from '@graphql-tools/federation';
export default class SupergraphHandler {
constructor({ config, baseDir, store, importFn, logger, }) {
this.config = config;
this.baseDir = baseDir;
this.supergraphSdl = store.proxy('nonExecutableSchema', PredefinedProxyOptions.JsonWithoutValidation);
this.importFn = importFn;
this.logger = logger;
}
async getSupergraphSdl() {
const schemaHeadersFactory = getInterpolatedHeadersFactory(this.config.schemaHeaders);
if (isUrl(this.config.source)) {
const interpolatedSource = stringInterpolator.parse(this.config.source, {
env: process.env,
});
const res = await readUrl(interpolatedSource, {
headers: schemaHeadersFactory({
env: process.env,
}),
cwd: this.baseDir,
allowUnknownExtensions: true,
importFn: this.importFn,
fetch: this.fetchFn,
logger: this.logger,
});
if (typeof res === 'string') {
return parse(res, { noLocation: true });
}
return res;
}
return this.supergraphSdl.getWithSet(async () => {
const interpolatedSource = stringInterpolator.parse(this.config.source, {
env: process.env,
});
const sdlOrIntrospection = await readFile(interpolatedSource, {
cwd: this.baseDir,
allowUnknownExtensions: true,
importFn: this.importFn,
fetch: this.fetchFn,
logger: this.logger,
});
if (typeof sdlOrIntrospection === 'string') {
return parse(sdlOrIntrospection, { noLocation: true });
}
return sdlOrIntrospection;
});
}
async getMeshSource({ fetchFn }) {
this.fetchFn = fetchFn;
const supergraphSdl = await this.getSupergraphSdl();
const operationHeadersFactory = this.config.operationHeaders != null
? getInterpolatedHeadersFactory(this.config.operationHeaders)
: undefined;
const schema = getStitchedSchemaFromSupergraphSdl({
supergraphSdl,
onExecutor: ({ endpoint }) => {
return buildHTTPExecutor({
endpoint,
fetch: fetchFn,
headers: operationHeadersFactory &&
(execReq => operationHeadersFactory({
env: process.env,
context: execReq.context,
})),
});
},
batch: this.config.batch == null ? true : this.config.batch,
});
return {
schema,
};
}
}