Skip to content

Commit c1205cf

Browse files
committed
refactor: Refactor AST visitor
1 parent 09d0e9e commit c1205cf

File tree

1 file changed

+109
-113
lines changed

1 file changed

+109
-113
lines changed

src/visitor.ts

+109-113
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,74 @@ export interface SWRPluginConfig extends ClientSideBasePluginConfig {
1818
autogenSWRKey: boolean
1919
}
2020

21+
export interface Operation {
22+
node: OperationDefinitionNode
23+
documentVariableName: string
24+
operationType: string
25+
operationResultType: string
26+
operationVariablesTypes: string
27+
}
28+
29+
export interface ComposeQueryHandlerConfig {
30+
autogenKey: boolean
31+
infinite: boolean
32+
rawRequest: boolean
33+
}
34+
35+
const composeQueryHandler = (
36+
operation: Operation,
37+
config: ComposeQueryHandlerConfig
38+
): string[] => {
39+
const codes: string[] = []
40+
const { node } = operation
41+
const optionalVariables =
42+
!node.variableDefinitions ||
43+
node.variableDefinitions.length === 0 ||
44+
node.variableDefinitions.every(
45+
(v) => v.type.kind !== Kind.NON_NULL_TYPE || v.defaultValue
46+
)
47+
? '?'
48+
: ''
49+
const name = node.name.value
50+
const pascalName = pascalCase(node.name.value)
51+
const responseType = config.rawRequest
52+
? `SWRRawResponse<${operation.operationResultType}>`
53+
: operation.operationResultType
54+
const variablesType = operation.operationVariablesTypes
55+
56+
codes.push(`use${pascalName}(${
57+
config.autogenKey ? '' : 'key: SWRKeyInterface, '
58+
}variables${optionalVariables}: ${variablesType}, config?: SWRConfigInterface<${responseType}>) {
59+
return useSWR<${responseType}>(${
60+
config.autogenKey
61+
? `genKey<${variablesType}>('${pascalName}', variables)`
62+
: 'key'
63+
}, () => sdk.${name}(variables), config);
64+
}`)
65+
66+
if (config.infinite) {
67+
codes.push(`use${pascalName}Infinite(${
68+
config.autogenKey ? '' : 'id: string, '
69+
}getKey: SWRInfiniteKeyLoader<${responseType}, ${variablesType}>, variables${optionalVariables}: ${variablesType}, config?: SWRInfiniteConfigInterface<${responseType}>) {
70+
return useSWRInfinite<${responseType}>(
71+
utilsForInfinite.generateGetKey<${responseType}, ${variablesType}>(${
72+
config.autogenKey
73+
? `genKey<${variablesType}>('${pascalName}', variables)`
74+
: 'id'
75+
}, getKey),
76+
utilsForInfinite.generateFetcher<${responseType}, ${variablesType}>(sdk.${name}, variables),
77+
config);
78+
}`)
79+
}
80+
81+
return codes
82+
}
83+
2184
export class SWRVisitor extends ClientSideBaseVisitor<
2285
RawSWRPluginConfig,
2386
SWRPluginConfig
2487
> {
25-
private _operationsToInclude: {
26-
node: OperationDefinitionNode
27-
documentVariableName: string
28-
operationType: string
29-
operationResultType: string
30-
operationVariablesTypes: string
31-
}[] = []
88+
private _operationsToInclude: Operation[] = []
3289

3390
private _enabledInfinite = false
3491

@@ -95,10 +152,11 @@ export class SWRVisitor extends ClientSideBaseVisitor<
95152
}
96153

97154
public get sdkContent(): string {
98-
const { excludeQueries, autogenSWRKey } = this.config
155+
const codes: string[] = []
156+
const { config } = this
99157
const disabledexcludeQueries =
100-
!excludeQueries ||
101-
(Array.isArray(excludeQueries) && !excludeQueries.length)
158+
!config.excludeQueries ||
159+
(Array.isArray(config.excludeQueries) && !config.excludeQueries.length)
102160
const allPossibleActions = this._operationsToInclude
103161
.filter((o) => {
104162
if (o.operationType !== 'Query') {
@@ -107,113 +165,42 @@ export class SWRVisitor extends ClientSideBaseVisitor<
107165
if (disabledexcludeQueries) {
108166
return true
109167
}
110-
const name = o.node.name.value
111-
return !glob.isMatch(name, excludeQueries)
112-
})
113-
.map((o) => {
114-
const optionalVariables =
115-
!o.node.variableDefinitions ||
116-
o.node.variableDefinitions.length === 0 ||
117-
o.node.variableDefinitions.every(
118-
(v) => v.type.kind !== Kind.NON_NULL_TYPE || v.defaultValue
119-
)
120-
const name = o.node.name.value
121-
const pascalName = pascalCase(o.node.name.value)
122-
const enabledInfinite =
123-
this._enabledInfinite &&
124-
glob.isMatch(name, this.config.useSWRInfinite)
125-
const codes: string[] = []
126-
127-
if (this.config.rawRequest) {
128-
codes.push(`use${pascalCase(o.node.name.value)}(${
129-
autogenSWRKey ? '' : 'key: SWRKeyInterface, '
130-
}variables${optionalVariables ? '?' : ''}: ${
131-
o.operationVariablesTypes
132-
}, config?: SWRConfigInterface<SWRRawResponse<${
133-
o.operationResultType
134-
}>}>) {
135-
return useSWR<SWRRawResponse<${o.operationResultType}>>(${
136-
autogenSWRKey
137-
? `genKey<${o.operationVariablesTypes}>('${pascalName}', variables)`
138-
: 'key'
139-
}, () => sdk.${o.node.name.value}(variables), config);
140-
}`)
141-
142-
if (enabledInfinite) {
143-
codes.push(`use${pascalCase(
144-
o.node.name.value
145-
)}Infinite(getKey: SWRInfiniteKeyLoader<SWRRawResponse<${
146-
o.operationResultType
147-
}>>, variables${optionalVariables ? '?' : ''}: ${
148-
o.operationVariablesTypes
149-
}, config?: SWRInfiniteConfigInterface<SWRRawResponse<${
150-
o.operationResultType
151-
}>>) {
152-
return useSWRInfinite<SWRRawResponse<${
153-
o.operationResultType
154-
}>>(getKey, () => sdk.${o.node.name.value}(variables), config);
155-
}`)
156-
}
157-
return codes
158-
}
159-
160-
codes.push(`use${pascalName}(${
161-
autogenSWRKey ? '' : 'key: SWRKeyInterface, '
162-
}variables${optionalVariables ? '?' : ''}: ${
163-
o.operationVariablesTypes
164-
}, config?: SWRConfigInterface<${o.operationResultType}>) {
165-
return useSWR<${o.operationResultType}>(${
166-
autogenSWRKey
167-
? `genKey<${o.operationVariablesTypes}>('${pascalName}', variables)`
168-
: 'key'
169-
}, () => sdk.${o.node.name.value}(variables), config);
170-
}`)
171-
172-
if (enabledInfinite) {
173-
codes.push(`use${pascalCase(
174-
o.node.name.value
175-
)}Infinite(id: string, getKey: SWRInfiniteKeyLoader<${
176-
o.operationResultType
177-
}, ${o.operationVariablesTypes}>, variables${
178-
optionalVariables ? '?' : ''
179-
}: ${
180-
o.operationVariablesTypes
181-
}, config?: SWRInfiniteConfigInterface<${o.operationResultType}>) {
182-
return useSWRInfinite<${o.operationResultType}>(
183-
utilsForInfinite.generateGetKey<${o.operationResultType}, ${
184-
o.operationVariablesTypes
185-
}>(id, getKey),
186-
utilsForInfinite.generateFetcher<${o.operationResultType}, ${
187-
o.operationVariablesTypes
188-
}>(sdk.${o.node.name.value}, variables),
189-
config);
190-
}`)
191-
}
192-
193-
return codes
168+
return !glob.isMatch(o.node.name.value, config.excludeQueries)
194169
})
170+
.map((o) =>
171+
composeQueryHandler(o, {
172+
autogenKey: config.autogenSWRKey,
173+
infinite:
174+
this._enabledInfinite &&
175+
glob.isMatch(o.node.name.value, config.useSWRInfinite),
176+
rawRequest: config.rawRequest,
177+
})
178+
)
195179
.reduce((p, c) => p.concat(c), [])
196180
.map((s) => indentMultiline(s, 2))
197181

198-
const types: string[] = []
199-
if (this.config.rawRequest) {
200-
types.push(
182+
// Add type of SWRRawResponse
183+
if (config.rawRequest) {
184+
codes.push(
201185
`type SWRRawResponse<Data = any> = { data?: Data | undefined; extensions?: any; headers: Headers; status: number; errors?: GraphQLError[] | undefined; };`
202186
)
203187
}
188+
189+
// Add type of SWRInfiniteKeyLoader
204190
if (this._enabledInfinite) {
205-
types.push(`export type SWRInfiniteKeyLoader<Data = unknown, Variables = unknown> = (
191+
codes.push(`export type SWRInfiniteKeyLoader<Data = unknown, Variables = unknown> = (
206192
index: number,
207193
previousPageData: Data | null
208194
) => [keyof Variables, Variables[keyof Variables] | null] | null;`)
209195
}
210196

211-
return `${types.join('\n')}
212-
export function getSdkWithHooks(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
213-
const sdk = getSdk(client, withWrapper);
214-
${
215-
this._enabledInfinite
216-
? ` const utilsForInfinite = {
197+
// Add getSdkWithHooks function
198+
codes.push(`export function getSdkWithHooks(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) {
199+
const sdk = getSdk(client, withWrapper);`)
200+
201+
// Add the utility for useSWRInfinite
202+
if (this._enabledInfinite) {
203+
codes.push(` const utilsForInfinite = {
217204
generateGetKey: <Data = unknown, Variables = unknown>(
218205
id: string,
219206
getKey: SWRInfiniteKeyLoader<Data, Variables>
@@ -226,17 +213,26 @@ ${
226213
fieldName: keyof Variables,
227214
fieldValue: Variables[typeof fieldName]
228215
) => query({ ...variables, [fieldName]: fieldValue } as Variables)
229-
}\n`
230-
: ''
231-
}${
232-
autogenSWRKey
233-
? ' 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])];\n'
234-
: ''
235-
} return {
216+
}`)
217+
}
218+
219+
// Add the function for auto-generation key for SWR
220+
if (config.autogenSWRKey) {
221+
codes.push(
222+
` 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])];`
223+
)
224+
}
225+
226+
// Add return statement for getSdkWithHooks function and close the function
227+
codes.push(` return {
236228
...sdk,
237229
${allPossibleActions.join(',\n')}
238230
};
239-
}
240-
export type SdkWithHooks = ReturnType<typeof getSdkWithHooks>;`
231+
}`)
232+
233+
// Add type of Sdk
234+
codes.push(`export type SdkWithHooks = ReturnType<typeof getSdkWithHooks>;`)
235+
236+
return codes.join('\n')
241237
}
242238
}

0 commit comments

Comments
 (0)