-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathvisitor.ts
More file actions
259 lines (233 loc) · 8.46 KB
/
Copy pathvisitor.ts
File metadata and controls
259 lines (233 loc) · 8.46 KB
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import {
ClientSideBasePluginConfig,
ClientSideBaseVisitor,
indentMultiline,
LoadedFragment,
ParsedConfig,
} from '@graphql-codegen/visitor-plugin-common'
import { GraphQLSchema, Kind, OperationDefinitionNode } from 'graphql'
import glob from 'micromatch'
import { pascalCase } from 'pascal-case'
import { RawSWRPluginConfig } from './config'
export interface SWRPluginConfig extends ClientSideBasePluginConfig {
rawRequest: boolean
excludeQueries: string | string[]
useSWRInfinite: string | string[]
autogenSWRKey: boolean
}
export interface Operation {
node: OperationDefinitionNode
documentVariableName: string
operationType: string
operationResultType: string
operationVariablesTypes: string
}
export interface ComposeQueryHandlerConfig {
autogenKey: SWRPluginConfig['autogenSWRKey']
infinite: boolean
rawRequest: SWRPluginConfig['rawRequest']
typesPrefix: ParsedConfig['typesPrefix']
typesSuffix: ParsedConfig['typesSuffix']
}
const composeQueryHandler = (
operation: Operation,
config: ComposeQueryHandlerConfig
): string[] => {
const codes: string[] = []
const { node } = operation
const optionalVariables =
!node.variableDefinitions ||
node.variableDefinitions.length === 0 ||
node.variableDefinitions.every(
(v) => v.type.kind !== Kind.NON_NULL_TYPE || v.defaultValue
)
? '?'
: ''
const name = node.name.value
const pascalName = pascalCase(node.name.value)
const responseType = config.rawRequest
? `SWRRawResponse<${operation.operationResultType}>`
: operation.operationResultType
const variablesType = operation.operationVariablesTypes
codes.push(`use${pascalName}(${
config.autogenKey ? '' : 'key: SWRKeyInterface, '
}variables${optionalVariables}: ${variablesType}, config?: SWRConfigInterface<${responseType}, ClientError>) {
return useSWR<${responseType}, ClientError>(${
config.autogenKey
? `genKey<${variablesType}>('${pascalName}', variables)`
: 'key'
}, () => sdk.${name}(variables), config);
}`)
if (config.infinite) {
codes.push(`use${pascalName}Infinite(${
config.autogenKey ? '' : 'id: string, '
}getKey: ${config.typesPrefix}SWRInfiniteKeyLoader${
config.typesSuffix
}<${responseType}, ${variablesType}>, variables${optionalVariables}: ${variablesType}, config?: SWRInfiniteConfiguration<${responseType}, ClientError>) {
return useSWRInfinite<${responseType}, ClientError>(
utilsForInfinite.generateGetKey<${responseType}, ${variablesType}>(${
config.autogenKey
? `genKey<${variablesType}>('${pascalName}', variables)`
: 'id'
}, getKey),
utilsForInfinite.generateFetcher<${responseType}, ${variablesType}>(sdk.${name}, variables),
config);
}`)
}
return codes
}
export class SWRVisitor extends ClientSideBaseVisitor<
RawSWRPluginConfig,
SWRPluginConfig
> {
private _operationsToInclude: Operation[] = []
private _enabledInfinite = false
constructor(
schema: GraphQLSchema,
fragments: LoadedFragment[],
rawConfig: RawSWRPluginConfig
) {
super(schema, fragments, rawConfig, {
excludeQueries: rawConfig.excludeQueries || null,
useSWRInfinite: rawConfig.useSWRInfinite || null,
autogenSWRKey: rawConfig.autogenSWRKey || false,
})
this._enabledInfinite =
(this.config.useSWRInfinite &&
typeof this.config.useSWRInfinite === 'string') ||
(Array.isArray(this.config.useSWRInfinite) &&
this.config.useSWRInfinite.length > 0)
const typeImport = this.config.useTypeImports ? 'import type' : 'import'
this._additionalImports.push(
`${typeImport} { ClientError } from 'graphql-request';`
)
if (this.config.useTypeImports) {
if (this._enabledInfinite) {
this._additionalImports.push(
`import type { SWRConfiguration as SWRConfigInterface, Key as SWRKeyInterface } from 'swr';`
)
this._additionalImports.push(
`import type { SWRInfiniteConfiguration } from 'swr/infinite';`
)
this._additionalImports.push(`import useSWR from 'swr';`)
this._additionalImports.push(
`import useSWRInfinite from 'swr/infinite';`
)
} else {
this._additionalImports.push(
`import type { SWRConfiguration as SWRConfigInterface, Key as SWRKeyInterface } from 'swr';`
)
this._additionalImports.push(`import useSWR from 'swr';`)
}
} else if (this._enabledInfinite) {
this._additionalImports.push(
`import useSWR, { SWRConfiguration as SWRConfigInterface, Key as SWRKeyInterface } from 'swr';`
)
this._additionalImports.push(
`import useSWRInfinite, { SWRInfiniteConfiguration } from 'swr/infinite';`
)
} else {
this._additionalImports.push(
`import useSWR, { SWRConfiguration as SWRConfigInterface, Key as SWRKeyInterface } from 'swr';`
)
}
}
protected buildOperation(
node: OperationDefinitionNode,
documentVariableName: string,
operationType: string,
operationResultType: string,
operationVariablesTypes: string
): string {
this._operationsToInclude.push({
node,
documentVariableName,
operationType,
operationResultType,
operationVariablesTypes,
})
return null
}
public get sdkContent(): string {
const codes: string[] = []
const { config } = this
const disabledexcludeQueries =
!config.excludeQueries ||
(Array.isArray(config.excludeQueries) && !config.excludeQueries.length)
const allPossibleActions = this._operationsToInclude
.filter((o) => {
if (o.operationType !== 'Query') {
return false
}
if (disabledexcludeQueries) {
return true
}
return !glob.isMatch(o.node.name.value, config.excludeQueries)
})
.map((o) =>
composeQueryHandler(o, {
autogenKey: config.autogenSWRKey,
infinite:
this._enabledInfinite &&
glob.isMatch(o.node.name.value, config.useSWRInfinite),
rawRequest: config.rawRequest,
typesPrefix: config.typesPrefix,
typesSuffix: config.typesSuffix,
})
)
.reduce((p, c) => p.concat(c), [])
.map((s) => indentMultiline(s, 2))
// Add type of SWRRawResponse
if (config.rawRequest) {
codes.push(
`type SWRRawResponse<Data = any> = { data?: Data | undefined; extensions?: any; headers: Headers; status: number; errors?: GraphQLError[] | undefined; };`
)
}
// Add type of SWRInfiniteKeyLoader
if (this._enabledInfinite) {
codes.push(`export type ${config.typesPrefix}SWRInfiniteKeyLoader${config.typesSuffix}<Data = unknown, Variables = unknown> = (
index: number,
previousPageData: Data | null
) => [keyof Variables, Variables[keyof Variables] | null] | null;`)
}
// Add getSdkWithHooks function
codes.push(`export function getSdkWithHooks(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
const sdk = getSdk(client, withWrapper);`)
// Add the utility for useSWRInfinite
if (this._enabledInfinite) {
codes.push(` const utilsForInfinite = {
generateGetKey: <Data = unknown, Variables = unknown>(
id: ${config.autogenSWRKey ? 'SWRKeyInterface' : 'string'},
getKey: ${config.typesPrefix}SWRInfiniteKeyLoader${
config.typesSuffix
}<Data, Variables>
) => (pageIndex: number, previousData: Data | null) => {
const key = getKey(pageIndex, previousData)
return key ? [id, ...key] : null
},
generateFetcher: <Query = unknown, Variables = unknown>(query: (variables: Variables) => Promise<Query>, variables?: Variables) => (
id: string,
fieldName: keyof Variables,
fieldValue: Variables[typeof fieldName]
) => query({ ...variables, [fieldName]: fieldValue } as Variables)
}`)
}
// Add the function for auto-generation key for SWR
if (config.autogenSWRKey) {
codes.push(
` const genKey = <V extends Record<string, unknown> = Record<string, unknown>>(name: string, object: V = {} as V): SWRKeyInterface => [name, ...Object.keys(object).sort().map(key => object[key])];`
)
}
// Add return statement for getSdkWithHooks function and close the function
codes.push(` return {
...sdk,
${allPossibleActions.join(',\n')}
};
}`)
// Add type of Sdk
codes.push(
`export type ${config.typesPrefix}SdkWithHooks${config.typesSuffix} = ReturnType<typeof getSdkWithHooks>;`
)
return codes.join('\n')
}
}