1 | import * as fs from 'fs';
|
2 |
|
3 | import { buildClientSchema, printSchema } from 'graphql';
|
4 |
|
5 | import { ToolError } from 'apollo-codegen-core/lib/errors'
|
6 | import { PrinterOptions } from 'graphql/utilities/schemaPrinter';
|
7 |
|
8 | export 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 | }
|