Last active
November 11, 2017 22:37
-
-
Save Francois-Esquire/a92f7e5b0eadc7bc3312f0df1d45824a to your computer and use it in GitHub Desktop.
importing .graphql schema files with #import statements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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