How to use the graphql.printSchema function in graphql

To help you get started, we’ve selected a few graphql examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lifeomic / json-schema-to-graphql-types / bin / convert-json-schemas-to-graphql-types.js View on Github external
// The directory comes from the command line argument
  // eslint-disable-next-line security/detect-non-literal-fs-filename
  const files = await validators.validatePathName(dir); // If valid, will return an array of file names
  const schemas = [];

  for (const file of files) {
    const schemaContents = await validators.validateJSONSyntax(file, dir); // If valid, will return parsed JSON-schema from file
    if (Array.isArray(schemaContents)) {
      schemaContents.forEach(oneSchema => schemas.push(oneSchema));
    } else {
      schemas.push(schemaContents);
    }
  }

  const schema = jsonSchemasToGraphqlSchema(schemas);
  const printed = printSchema(schema);

  // Strip out the Query type because it's not needed
  const withoutQuery = printed.replace(/^type Query {[^}]*}/m, '');
  const withoutMutation = withoutQuery.replace(/^type Mutation {[^}]*}/m, '');

  if (asJs) {
    console.log(`'use strict';\nmodule.exports = \`\n${withoutMutation}\`;\n`);
  } else {
    console.log(withoutQuery);
  }
}
github moleculerjs / moleculer-apollo-server / src / service.js View on Github external
if (!this.shouldUpdateGraphqlSchema && this.graphqlHandler) {
					return;
				}

				// Create new server & regenerate GraphQL schema
				this.logger.info(
					"♻ Recreate Apollo GraphQL server and regenerate GraphQL schema..."
				);

				try {
					this.pubsub = new PubSub();
					const services = this.broker.registry.getServiceList({ withActions: true });
					const schema = this.generateGraphQLSchema(services);

					this.logger.debug(
						"Generated GraphQL schema:\n\n" + GraphQL.printSchema(schema)
					);

					this.apolloServer = new ApolloServer({
						schema,
						..._.defaultsDeep({}, mixinOptions.serverOptions, {
							context: ({ req, connection }) => {
								return req
									? {
											ctx: req.$ctx,
											service: req.$service,
											params: req.$params,
											loaders: this.createLoaders(req, services),
									  }
									: {
											service: connection.$service,
									  };
github graphql-compose / graphql-compose-aws / examples / introspection / generate.js View on Github external
/* @flow */

import fs from 'fs';
import path from 'path';
import { printSchema } from 'graphql';
import schema from '../fullApi/schema';

const output = path.resolve(__dirname, './schema.txt');
fs.writeFileSync(output, printSchema(schema));
github Urigo / graphql-cli / src / cmds / get-schema.ts View on Github external
: ''
            }No changes`,
          ),
        )
        emitter.emit('checked')
        return
      }
    }
  }

  let schemaPath = argv.output
  if (argv.console) {
    console.log(
      argv.json
        ? JSON.stringify(newSchemaResult, null, 2)
        : printSchema(newSchemaResult as GraphQLSchema),
    )
  } else if (argv.json) {
    if (!fs.existsSync(schemaPath)) {
      mkdirp.sync(dirname(schemaPath))
    }
    fs.writeFileSync(argv.output, JSON.stringify(newSchemaResult, null, 2))
  } else {
    schemaPath = schemaPath || config!.schemaPath
    if (!fs.existsSync(schemaPath)) {
      mkdirp.sync(dirname(schemaPath))
    }
    await writeSchema(schemaPath as string, newSchemaResult as GraphQLSchema, {
      source: endpoint.url,
      timestamp: new Date().toString(),
    })
  }
github benawad / apollo-mocked-provider / src / fetchTypeDefs.ts View on Github external
export const fetchTypeDefs = async ({
  uri = 'http://localhost:4000/graphql',
  typescript = true,
  path = `${process.cwd()}/typeDefs.${typescript ? 'ts' : 'js'}`,
}: FetchTypeDefOptions) => {
  const link = new HttpLink({ uri, fetch });

  console.log('writing typeDefs to: ', path);

  fs.writeFileSync(
    path,
    `export const typeDefs = \`
${printSchema((await introspectSchema(link)) as any).replace(/`/g, '\\`')}\``
  );
};
github prisma-labs / prisma-binding / src / bin.ts View on Github external
break
    case 'flow':
      generatorInstance = new PrismaFlowGenerator(args)
      break
    default:
      generatorInstance = new PrismaGenerator(args)
  }

  const code = generatorInstance.render()

  mkdirp(path.dirname(outputBinding))
  fs.writeFileSync(outputBinding, code)

  if (outputTypedefs) {
    mkdirp(path.dirname(outputTypedefs))
    fs.writeFileSync(outputTypedefs, printSchema(schema))
  }

  console.log('Done generating binding')
}
github aerogear / graphback / packages / graphback-schema / src / plugin.ts View on Github external
export const plugin = (schema: GraphQLSchema) => {

  const inputContext = new GraphbackContextCreator(printSchema(schema)).createInputContext()

  const context: TargetContext = buildTargetContext(inputContext.reverse())

  return generateSchema(context)
}
github kgoggin / reason-react-apollo / packages / codegen-reason-client / src / index.ts View on Github external
export const plugin: PluginFunction = async (
  schema: GraphQLSchema,
  documents: Types.DocumentFile[],
  c: BaseReasonConfig
) => {
  const printedSchema = printSchema(schema);
  const astNode = parse(printedSchema);
  const config = { ...defaultBaseConfig, ...c };

  const visitor = makeVisitor(config, (data: ISchemaData) => {
    const { inputObjects, objects, enums } = data;
    const inputObjectTypeDefs =
      (inputObjects.length &&
        `type ${inputObjects.map(writeInputType).join(' and \n')};`) ||
      '';

    return `
    ${head(config)}
    ${writeCustomScalars(config)}
    ${enums.map(writeEnumType).join('\n')}
    ${objects.map(writeObjectType(config)).join('\n')}
    ${inputObjectTypeDefs}
github bradleyboy / tuql / src / bin / index.js View on Github external
  promise.then(schema => process.stdout.write(printSchema(schema)));
} else {