UNPKG

7.69 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.ReactQueryVisitor = void 0;
4const tslib_1 = require("tslib");
5const visitor_plugin_common_1 = require("@graphql-codegen/visitor-plugin-common");
6const variables_generator_js_1 = require("./variables-generator.js");
7const fetcher_custom_mapper_js_1 = require("./fetcher-custom-mapper.js");
8const fetcher_fetch_js_1 = require("./fetcher-fetch.js");
9const fetcher_graphql_request_js_1 = require("./fetcher-graphql-request.js");
10const fetcher_fetch_hardcoded_js_1 = require("./fetcher-fetch-hardcoded.js");
11const auto_bind_1 = tslib_1.__importDefault(require("auto-bind"));
12const change_case_all_1 = require("change-case-all");
13class ReactQueryVisitor extends visitor_plugin_common_1.ClientSideBaseVisitor {
14 constructor(schema, fragments, rawConfig, documents) {
15 super(schema, fragments, rawConfig, {
16 documentMode: visitor_plugin_common_1.DocumentMode.string,
17 errorType: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.errorType, 'unknown'),
18 exposeDocument: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.exposeDocument, false),
19 exposeQueryKeys: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.exposeQueryKeys, false),
20 exposeMutationKeys: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.exposeMutationKeys, false),
21 exposeFetcher: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.exposeFetcher, false),
22 addInfiniteQuery: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.addInfiniteQuery, false),
23 legacyMode: (0, visitor_plugin_common_1.getConfigValue)(rawConfig.legacyMode, false),
24 });
25 this.rawConfig = rawConfig;
26 this.reactQueryHookIdentifiersInUse = new Set();
27 this.reactQueryOptionsIdentifiersInUse = new Set();
28 this.queryMethodMap = {
29 infiniteQuery: {
30 hook: 'useInfiniteQuery',
31 options: 'UseInfiniteQueryOptions',
32 },
33 query: {
34 hook: 'useQuery',
35 options: 'UseQueryOptions',
36 },
37 mutation: {
38 hook: 'useMutation',
39 options: 'UseMutationOptions',
40 },
41 };
42 this._externalImportPrefix = this.config.importOperationTypesFrom ? `${this.config.importOperationTypesFrom}.` : '';
43 this._documents = documents;
44 this.fetcher = this.createFetcher(rawConfig.fetcher || 'fetch');
45 (0, auto_bind_1.default)(this);
46 }
47 get imports() {
48 return this._imports;
49 }
50 createFetcher(raw) {
51 if (raw === 'fetch') {
52 return new fetcher_fetch_js_1.FetchFetcher(this);
53 }
54 if (typeof raw === 'object' && 'endpoint' in raw) {
55 return new fetcher_fetch_hardcoded_js_1.HardcodedFetchFetcher(this, raw);
56 }
57 if (raw === 'graphql-request') {
58 return new fetcher_graphql_request_js_1.GraphQLRequestClientFetcher(this);
59 }
60 return new fetcher_custom_mapper_js_1.CustomMapperFetcher(this, raw);
61 }
62 get hasOperations() {
63 return this._collectedOperations.length > 0;
64 }
65 getImports() {
66 const baseImports = super.getImports();
67 if (!this.hasOperations) {
68 return baseImports;
69 }
70 const hookAndTypeImports = [
71 ...Array.from(this.reactQueryHookIdentifiersInUse),
72 ...Array.from(this.reactQueryOptionsIdentifiersInUse).map(identifier => `${this.config.useTypeImports ? 'type ' : ''}${identifier}`),
73 ];
74 const moduleName = this.config.legacyMode ? 'react-query' : '@tanstack/react-query';
75 return [...baseImports, `import { ${hookAndTypeImports.join(', ')} } from '${moduleName}';`];
76 }
77 getFetcherImplementation() {
78 return this.fetcher.generateFetcherImplementaion();
79 }
80 _getHookSuffix(name, operationType) {
81 if (this.config.omitOperationSuffix) {
82 return '';
83 }
84 if (!this.config.dedupeOperationSuffix) {
85 return (0, change_case_all_1.pascalCase)(operationType);
86 }
87 if (name.includes('Query') || name.includes('Mutation') || name.includes('Subscription')) {
88 return '';
89 }
90 return (0, change_case_all_1.pascalCase)(operationType);
91 }
92 buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes, hasRequiredVariables) {
93 var _a, _b;
94 const nodeName = (_b = (_a = node.name) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : '';
95 const suffix = this._getHookSuffix(nodeName, operationType);
96 const operationName = this.convertName(nodeName, {
97 suffix,
98 useTypesPrefix: false,
99 useTypesSuffix: false,
100 });
101 operationResultType = this._externalImportPrefix + operationResultType;
102 operationVariablesTypes = this._externalImportPrefix + operationVariablesTypes;
103 if (operationType === 'Query') {
104 let query = this.fetcher.generateQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
105 if (this.config.exposeDocument) {
106 query += `\nuse${operationName}.document = ${documentVariableName};\n`;
107 }
108 if (this.config.exposeQueryKeys) {
109 query += `\n${(0, variables_generator_js_1.generateQueryKeyMaker)(node, operationName, operationVariablesTypes, hasRequiredVariables)};\n`;
110 }
111 if (this.config.addInfiniteQuery) {
112 query += `\n${this.fetcher.generateInfiniteQueryHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables)}\n`;
113 if (this.config.exposeQueryKeys) {
114 query += `\n${(0, variables_generator_js_1.generateInfiniteQueryKeyMaker)(node, operationName, operationVariablesTypes, hasRequiredVariables)};\n`;
115 }
116 }
117 // The reason we're looking at the private field of the CustomMapperFetcher to see if it's a react hook
118 // is to prevent calling generateFetcherFetch for each query since all the queries won't be able to generate
119 // a fetcher field anyways.
120 if (this.config.exposeFetcher && !this.fetcher._isReactHook) {
121 query += this.fetcher.generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
122 }
123 return query;
124 }
125 if (operationType === 'Mutation') {
126 let query = this.fetcher.generateMutationHook(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
127 if (this.config.exposeMutationKeys) {
128 query += (0, variables_generator_js_1.generateMutationKeyMaker)(node, operationName);
129 }
130 if (this.config.exposeFetcher && !this.fetcher._isReactHook) {
131 query += this.fetcher.generateFetcherFetch(node, documentVariableName, operationName, operationResultType, operationVariablesTypes, hasRequiredVariables);
132 }
133 return query;
134 }
135 if (operationType === 'Subscription') {
136 // eslint-disable-next-line no-console
137 console.warn(`Plugin "typescript-react-query" does not support GraphQL Subscriptions at the moment! Ignoring "${node.name.value}"...`);
138 }
139 return null;
140 }
141}
142exports.ReactQueryVisitor = ReactQueryVisitor;