UNPKG

1.55 kBJavaScriptView Raw
1import { Kind, concatAST } from 'graphql';
2import { oldVisit } from '@graphql-codegen/plugin-helpers';
3import { ReactQueryVisitor } from './visitor.js';
4import { extname } from 'path';
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 ReactQueryVisitor(schema, allFragments, config, documents);
17 const visitorResult = oldVisit(allAst, { leave: visitor });
18 if (visitor.hasOperations) {
19 return {
20 prepend: [...visitor.getImports(), visitor.getFetcherImplementation()],
21 content: [visitor.fragments, ...visitorResult.definitions.filter(t => typeof t === 'string')].join('\n'),
22 };
23 }
24 return {
25 prepend: [...visitor.getImports()],
26 content: [visitor.fragments, ...visitorResult.definitions.filter(t => typeof t === 'string')].join('\n'),
27 };
28};
29export const validate = async (schema, documents, config, outputFile) => {
30 if (extname(outputFile) !== '.ts' && extname(outputFile) !== '.tsx') {
31 throw new Error(`Plugin "typescript-react-query" requires extension to be ".ts" or ".tsx"!`);
32 }
33};
34export { ReactQueryVisitor };