Skip to content

Instantly share code, notes, and snippets.

@Francois-Esquire
Last active November 11, 2017 22:37
Show Gist options
  • Save Francois-Esquire/a92f7e5b0eadc7bc3312f0df1d45824a to your computer and use it in GitHub Desktop.
Save Francois-Esquire/a92f7e5b0eadc7bc3312f0df1d45824a to your computer and use it in GitHub Desktop.
importing .graphql schema files with #import statements
const fs = require('fs');
const { graphql, buildSchema, introspectionQuery } = require('graphql');
const importSchema = require('./importSchema');
module.exports = async function buildSchemaDocument({
// schema.graphql
schemaPath,
// schema.json
outputPath,
}) {
const schemaDef = importSchema(schemaPath);
const introspection = await graphql(buildSchema(schemaDef), introspectionQuery);
const json = JSON.stringify(introspection, undefined, 2);
fs.writeFileSync(outputPath, json, 'utf8');
};
const os = require('os');
const fs = require('fs');
const path = require('path');
function getPath(pathname, base) {
return path.isAbsolute(pathname) ?
pathname : path.resolve(base, pathname);
}
module.exports = function importSchema(pathname) {
// read the schema file.
const schema = fs.readFileSync(getPath(pathname)).toString();
// grab the base for relative imports.
const dirname = path.dirname(pathname);
return schema
// split line-by-line | inspired by graphql-tag/loader.
.split(/\r\n|\r|\n/)
// go through each line and inject in the import.
.map((statement) => {
// test if it matches import statement.
if (/^#import.*/.test(statement)) {
// strip to the bare path.
const importPath = statement.replace(/#import|['"\s]+/g, '');
// grab the full path.
const pathToSchema = getPath(dirname, importPath);
// recursively check each import for its own imports.
const seam = importSchema(pathToSchema);
// replace the import statement with the seam.
return seam;
// or return the original line.
} return statement;
})
// stitch all the seams together.
.join(os.EOL);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment