<|start_filename|>bin/bin.js<|end_filename|>
#!/usr/bin/env node
const chalk = require('chalk');
const graphqlToJson = require('../index.js');
const util = require('../util.js');
const args = process.argv.slice(2);
const output = (args[1]) ? util.normalizePath(args[1]) : 'schema.json';
graphqlToJson({input: args[0], output})
  .then(() => chalk.green(`'${output}' successfully created`))
  .catch(err => chalk.red(err))
  .then(str => process.stdout.write(str));


<|start_filename|>util.js<|end_filename|>
const path = require('path');

module.exports = {
  normalizePath: (output) => {
    if (path.extname(output) === ''){
      return path.join(output, 'schema.json');
    }
    return output;
  }
};


<|start_filename|>package.json<|end_filename|>
{
  "name": "graphql-to-json",
  "bin": {
    "graphql-to-json": "./bin/bin.js"
  },
  "version": "1.1.3",
  "description": "Generate a JSON representation of your GraphQL schema",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "graphql",
    "json",
    "cli"
  ],
  "author": "<NAME>",
  "license": "MIT",
  "dependencies": {},
  "repository": {
    "type": "git",
    "url": "git+https://github.com/WaldoJeffers/graphql-to-json.git"
  },
  "bugs": {
    "url": "https://github.com/WaldoJeffers/graphql-to-json/issues"
  },
  "homepage": "https://github.com/WaldoJeffers/graphql-to-json#readme"
}


<|start_filename|>index.js<|end_filename|>
const fs = require('fs');
const path = require('path');
const util = require('./util.js');

module.exports = ({input, output}, cb = () => {}) => {
  // INPUT
  if (!input){
    throw new Error('You must provide an input path.');
  }
  const filepath = path.resolve(input);
  const schema = require(filepath);
  // Ugly hack. Since graphql uses instanceof everywhere, the schema we require is not considered a valid graphql Schema because it was not created with the graphql module installed in this module We have to retrieve the "original" graphql module
  const loaded_module = module.children.find(mod => path.normalize(mod.id) === filepath);
  const graphql = loaded_module.children.find(mod => mod.exports.graphql).exports;
  // OUTPUT
  if (output){
    output = util.normalizePath(output);
  }

  // WRITE
  return graphql
    .graphql(schema, graphql.introspectionQuery)
    .then(result => JSON.stringify(result, null, 2))
    .then(json => {
      if (output){
        return new Promise((resolve, reject) => fs.writeFile(output, json, (err) => {
          if (err){
            return reject(err);
          }
          cb(json);
          resolve(json);
        }));
      }
      return json;
    });
};
