UNPKG

872 BPlain TextView Raw
1import * as fs from 'fs';
2
3import { buildClientSchema, printSchema } from 'graphql';
4
5import { ToolError } from 'apollo-codegen-core/lib/errors'
6import { PrinterOptions } from 'graphql/utilities/schemaPrinter';
7
8export default async function printSchemaFromIntrospectionResult(
9 schemaPath: string,
10 outputPath: string,
11 options?: PrinterOptions
12) {
13 if (!fs.existsSync(schemaPath)) {
14 throw new ToolError(`Cannot find GraphQL schema file: ${schemaPath}`);
15 }
16
17 const schemaJSON = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
18
19 if (!schemaJSON.data) {
20 throw new ToolError(`No introspection query result data found in: ${schemaPath}`);
21 }
22
23 const schema = buildClientSchema(schemaJSON.data);
24 const schemaIDL = printSchema(schema, options);
25
26 if (outputPath) {
27 fs.writeFileSync(outputPath, schemaIDL);
28 } else {
29 console.log(schemaIDL);
30 }
31}