/
visitor.ts
156 lines (124 loc) · 7.72 KB
/
visitor.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { ClientSideBaseVisitor, ClientSideBasePluginConfig, getConfigValue, LoadedFragment, OMIT_TYPE } from '@graphql-codegen/visitor-plugin-common';
import { ReactApolloRawPluginConfig } from './index';
import * as autoBind from 'auto-bind';
import { OperationDefinitionNode, Kind } from 'graphql';
import { toPascalCase } from '@graphql-codegen/plugin-helpers';
import { titleCase } from 'change-case';
export interface ReactApolloPluginConfig extends ClientSideBasePluginConfig {
withHOC: boolean;
withComponent: boolean;
withHooks: boolean;
withMutationFn: boolean;
hooksImportFrom: string;
reactApolloImportFrom: string;
componentSuffix: string;
reactApolloVersion: 2 | 3;
}
export class ReactApolloVisitor extends ClientSideBaseVisitor<ReactApolloRawPluginConfig, ReactApolloPluginConfig> {
constructor(fragments: LoadedFragment[], rawConfig: ReactApolloRawPluginConfig) {
super(fragments, rawConfig, {
componentSuffix: getConfigValue(rawConfig.componentSuffix, 'Component'),
withHOC: getConfigValue(rawConfig.withHOC, true),
withComponent: getConfigValue(rawConfig.withComponent, true),
withHooks: getConfigValue(rawConfig.withHooks, false),
withMutationFn: getConfigValue(rawConfig.withMutationFn, true),
hooksImportFrom: getConfigValue(rawConfig.hooksImportFrom, 'react-apollo-hooks'),
reactApolloImportFrom: getConfigValue(rawConfig.reactApolloImportFrom, 'react-apollo'),
reactApolloVersion: getConfigValue(rawConfig.reactApolloVersion, 2),
} as any);
autoBind(this);
}
private imports = new Set<string>();
private getReactImport(): string {
return `import * as React from 'react';`;
}
private getReactApolloImport(): string {
return `import * as ReactApollo from '${typeof this.config.reactApolloImportFrom === 'string' ? this.config.reactApolloImportFrom : 'react-apollo'}';`;
}
private getReactApolloHooksImport(): string {
return `import * as ReactApolloHooks from '${typeof this.config.hooksImportFrom === 'string' ? this.config.hooksImportFrom : 'react-apollo-hooks'}';`;
}
private getOmitDeclaration(): string {
return OMIT_TYPE;
}
public getImports(): string[] {
const baseImports = super.getImports();
const hasOperations = this._collectedOperations.length > 0;
if (!hasOperations) {
return baseImports;
}
return [...baseImports, ...this.imports];
}
private _buildHocProps(operationName: string, operationType: string): string {
const typeVariableName = this.convertName(operationName + toPascalCase(operationType));
const variablesVarName = this.convertName(operationName + toPascalCase(operationType) + 'Variables');
const argType = operationType === 'mutation' ? 'MutateProps' : 'DataProps';
this.imports.add(this.getReactApolloImport());
return `Partial<ReactApollo.${argType}<${typeVariableName}, ${variablesVarName}>>`;
}
private _buildMutationFn(node: OperationDefinitionNode, operationResultType: string, operationVariablesTypes: string): string {
if (node.operation === 'mutation') {
this.imports.add(this.getReactApolloImport());
return `export type ${this.convertName(node.name.value + 'MutationFn')} = ReactApollo.${MutationFnNameForVersionMap[this.config.reactApolloVersion]}<${operationResultType}, ${operationVariablesTypes}>;`;
}
return null;
}
private _buildOperationHoc(node: OperationDefinitionNode, documentVariableName: string, operationResultType: string, operationVariablesTypes: string): string {
const operationName: string = this.convertName(node.name.value, { useTypesPrefix: false });
const propsTypeName: string = this.convertName(node.name.value, { suffix: 'Props' });
const propsVar = `export type ${propsTypeName}<TChildProps = {}> = ${this._buildHocProps(node.name.value, node.operation)} & TChildProps;`;
const hocString = `export function with${operationName}<TProps, TChildProps = {}>(operationOptions?: ReactApollo.OperationOption<
TProps,
${operationResultType},
${operationVariablesTypes},
${propsTypeName}<TChildProps>>) {
return ReactApollo.with${titleCase(node.operation)}<TProps, ${operationResultType}, ${operationVariablesTypes}, ${propsTypeName}<TChildProps>>(${documentVariableName}, {
alias: 'with${operationName}',
...operationOptions
});
};`;
return [propsVar, hocString].filter(a => a).join('\n');
}
private _buildComponent(node: OperationDefinitionNode, documentVariableName: string, operationType: string, operationResultType: string, operationVariablesTypes: string): string {
const componentPropsName: string = this.convertName(node.name.value, { suffix: this.config.componentSuffix + 'Props', useTypesPrefix: false });
const componentName: string = this.convertName(node.name.value, { suffix: this.config.componentSuffix, useTypesPrefix: false });
const isVariablesRequired = operationType === 'Query' && node.variableDefinitions.some(variableDef => variableDef.type.kind === Kind.NON_NULL_TYPE);
this.imports.add(this.getReactImport());
this.imports.add(this.getReactApolloImport());
this.imports.add(this.getOmitDeclaration());
const propsType = `Omit<ReactApollo.${operationType}Props<${operationResultType}, ${operationVariablesTypes}>, '${operationType.toLowerCase()}'>`;
let componentProps = '';
if (isVariablesRequired) {
componentProps = `export type ${componentPropsName} = ${propsType} & ({ variables: ${operationVariablesTypes}; skip?: false; } | { skip: true; });`;
} else {
componentProps = `export type ${componentPropsName} = ${propsType};`;
}
const component = `
export const ${componentName} = (props: ${componentPropsName}) => (
<ReactApollo.${operationType}<${operationResultType}, ${operationVariablesTypes}> ${node.operation}={${documentVariableName}} {...props} />
);
`;
return [componentProps, component].join('\n');
}
private _buildHooks(node: OperationDefinitionNode, operationType: string, documentVariableName: string, operationResultType: string, operationVariablesTypes: string): string {
const operationName: string = this.convertName(node.name.value, { suffix: titleCase(operationType), useTypesPrefix: false });
this.imports.add(this.getReactApolloHooksImport());
const hookFn = `
export function use${operationName}(baseOptions?: ReactApolloHooks.${operationType}HookOptions<${this.config.hooksImportFrom === '@apollo/react-hooks' || node.operation !== 'query' ? `${operationResultType}, ` : ''}${operationVariablesTypes}>) {
return ReactApolloHooks.use${operationType}<${operationResultType}, ${operationVariablesTypes}>(${documentVariableName}, baseOptions);
};`;
const hookResult = `export type ${operationName}HookResult = ReturnType<typeof use${operationName}>;`;
return [hookFn, hookResult].join('\n');
}
protected buildOperation(node: OperationDefinitionNode, documentVariableName: string, operationType: string, operationResultType: string, operationVariablesTypes: string): string {
const mutationFn = this.config.withMutationFn || this.config.withComponent ? this._buildMutationFn(node, operationResultType, operationVariablesTypes) : null;
const component = this.config.withComponent ? this._buildComponent(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) : null;
const hoc = this.config.withHOC ? this._buildOperationHoc(node, documentVariableName, operationResultType, operationVariablesTypes) : null;
const hooks = this.config.withHooks ? this._buildHooks(node, operationType, documentVariableName, operationResultType, operationVariablesTypes) : null;
return [mutationFn, component, hoc, hooks].filter(a => a).join('\n');
}
}
const MutationFnNameForVersionMap = {
2: 'MutationFn',
3: 'MutationFunction',
};