-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
index.ts
34 lines (31 loc) · 1.34 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
import { Types, PluginValidateFn, PluginFunction } from '@graphql-codegen/plugin-helpers';
import { parse, GraphQLSchema, OperationDefinitionNode } from 'graphql';
import { pascalCase } from 'change-case';
import { extname } from 'path';
export const plugin: PluginFunction<{}> = (schema: GraphQLSchema, documents: Types.DocumentFile[], config) => {
return {
prepend: [`import { TypedDocumentNode } from '@graphql-typed-document-node/core';`],
content: documents
.map(docFile => {
const operation = docFile.document.definitions[0] as OperationDefinitionNode;
const resultTypeName = pascalCase(operation.name.value) + pascalCase(operation.operation);
const variablesTypeName = pascalCase(operation.name.value) + pascalCase(operation.operation) + 'Variables';
return `export const ${operation.name.value}${pascalCase(
operation.operation
)}: TypedDocumentNode<${resultTypeName}, ${variablesTypeName}> = ${JSON.stringify(
parse(docFile.rawSDL, { noLocation: true })
)};`;
})
.join('\n'),
};
};
export const validate: PluginValidateFn<any> = async (
schema: GraphQLSchema,
documents: Types.DocumentFile[],
config,
outputFile: string
) => {
if (extname(outputFile) !== '.ts') {
throw new Error(`Plugin "typed-document-node" requires extension to be ".ts"!`);
}
};