-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
36 lines (32 loc) · 1.49 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import type { CodegenPlugin } from '@graphql-codegen/plugin-helpers';
import { printSchemaWithDirectives } from '@graphql-tools/utils';
import { parse } from 'graphql';
import * as path from 'node:path';
interface TypescriptSchemaPluginConfig {
schemaRepresentation?: 'dsl' | 'ast';
}
const plugin: CodegenPlugin<TypescriptSchemaPluginConfig> = {
plugin(schema, _documents, config, info) {
const isTs = ['.ts', '.tsx'].includes(path.extname(info?.outputFile ?? ''));
const asAny = isTs ? ' as any' : '';
const { schemaRepresentation = 'ast' } = config;
if (schemaRepresentation === 'dsl') {
return {
prepend: ['import { buildSchema } from \'graphql\';'],
content: `export const schema = buildSchema(${JSON.stringify(printSchemaWithDirectives(schema))});\n`,
};
} else if (schemaRepresentation === 'ast') {
return {
prepend: ['import { buildASTSchema } from \'graphql\';'],
content: `export const schema = buildASTSchema(${JSON.stringify(parse(printSchemaWithDirectives(schema)))}${asAny});\n`,
};
}
throw new Error(`Invalid representation type is specified: ${schemaRepresentation}. Only 'dsl' or 'ast' are supported.`);
},
validate(_schema, _documents, config) {
if (config.schemaRepresentation && !['dsl', 'ast'].includes(config.schemaRepresentation)) {
throw new Error(`Invalid representation type is specified: ${config.schemaRepresentation}. Only 'dsl' or 'ast' are supported.`);
}
},
};
export = plugin;