UNPKG

1.55 kBJavaScriptView Raw
1import { extname } from 'path';
2import { concatAST, Kind } from 'graphql';
3import { oldVisit } from '@graphql-codegen/plugin-helpers';
4import { ReactApolloVisitor } from './visitor.js';
5export const plugin = (schema, documents, config) => {
6 const allAst = concatAST(documents.map(v => v.document));
7 const allFragments = [
8 ...allAst.definitions.filter(d => d.kind === Kind.FRAGMENT_DEFINITION).map(fragmentDef => ({
9 node: fragmentDef,
10 name: fragmentDef.name.value,
11 onType: fragmentDef.typeCondition.name.value,
12 isExternal: false,
13 })),
14 ...(config.externalFragments || []),
15 ];
16 const visitor = new ReactApolloVisitor(schema, allFragments, config, documents);
17 const visitorResult = oldVisit(allAst, { leave: visitor });
18 return {
19 prepend: visitor.getImports(),
20 content: [
21 visitor.fragments,
22 ...visitorResult.definitions.filter(t => typeof t === 'string'),
23 ].join('\n'),
24 };
25};
26export const validate = async (schema, documents, config, outputFile) => {
27 if (config.withComponent === true) {
28 if (extname(outputFile) !== '.tsx') {
29 throw new Error(`Plugin "typescript-react-apollo" requires extension to be ".tsx" when withComponent: true is set!`);
30 }
31 }
32 else if (extname(outputFile) !== '.ts' && extname(outputFile) !== '.tsx') {
33 throw new Error(`Plugin "typescript-react-apollo" requires extension to be ".ts" or ".tsx"!`);
34 }
35};
36export { ReactApolloVisitor };