@graphql-mesh/transform-extend
Version:
62 lines (58 loc) • 2.25 kB
JavaScript
;
const crossHelpers = require('@graphql-mesh/cross-helpers');
const codeFileLoader = require('@graphql-tools/code-file-loader');
const graphqlFileLoader = require('@graphql-tools/graphql-file-loader');
const load = require('@graphql-tools/load');
const schema = require('@graphql-tools/schema');
const utils = require('@graphql-tools/utils');
function loadFromModuleExportExpressionSync({ expression, defaultExportName, cwd, }) {
if (typeof expression !== 'string') {
return expression;
}
const [modulePath, exportName = defaultExportName] = expression.split('#');
const mod = tryRequire(modulePath, cwd);
return mod[exportName] || (mod.default && mod.default[exportName]) || mod.default || mod;
}
function tryRequire(modulePath, cwd) {
try {
return require(modulePath);
}
catch (_a) {
if (!crossHelpers.path.isAbsolute(modulePath)) {
const absoluteModulePath = crossHelpers.path.isAbsolute(modulePath) ? modulePath : crossHelpers.path.join(cwd, modulePath);
return require(absoluteModulePath);
}
}
}
class ExtendTransform {
constructor({ baseDir, config }) {
this.noWrap = true;
this.config = config;
this.baseDir = baseDir;
}
transformSchema(schema$1) {
const sources = load.loadTypedefsSync(this.config.typeDefs, {
cwd: crossHelpers.path.isAbsolute(this.config.typeDefs) ? null : this.baseDir,
loaders: [new codeFileLoader.CodeFileLoader(), new graphqlFileLoader.GraphQLFileLoader()],
});
const typeDefs = sources.map(source => source.document);
const resolvers = utils.asArray(this.config.resolvers).map(resolverDef => {
if (typeof resolverDef === 'string') {
return loadFromModuleExportExpressionSync({
expression: resolverDef,
defaultExportName: 'default',
cwd: this.baseDir,
});
}
else {
return resolverDef;
}
});
return schema.mergeSchemas({
schemas: [schema$1],
typeDefs,
resolvers,
});
}
}
module.exports = ExtendTransform;