@kubb/plugin-swr 3.0.0-alpha.9 → 3.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +14 -5
  2. package/dist/chunk-4EGGCGSE.js +217 -0
  3. package/dist/chunk-4EGGCGSE.js.map +1 -0
  4. package/dist/chunk-H23WKEYP.js +243 -0
  5. package/dist/chunk-H23WKEYP.js.map +1 -0
  6. package/dist/chunk-JWGWABV5.cjs +249 -0
  7. package/dist/chunk-JWGWABV5.cjs.map +1 -0
  8. package/dist/chunk-PTOQHHST.cjs +220 -0
  9. package/dist/chunk-PTOQHHST.cjs.map +1 -0
  10. package/dist/components.cjs +23 -6
  11. package/dist/components.cjs.map +1 -1
  12. package/dist/components.d.cts +88 -6
  13. package/dist/components.d.ts +88 -6
  14. package/dist/components.js +2 -10
  15. package/dist/components.js.map +1 -1
  16. package/dist/generators.cjs +17 -0
  17. package/dist/generators.cjs.map +1 -0
  18. package/dist/generators.d.cts +11 -0
  19. package/dist/generators.d.ts +11 -0
  20. package/dist/generators.js +4 -0
  21. package/dist/generators.js.map +1 -0
  22. package/dist/index.cjs +93 -123
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +2 -4
  25. package/dist/index.d.ts +2 -4
  26. package/dist/index.js +77 -114
  27. package/dist/index.js.map +1 -1
  28. package/dist/types-DaH2Sc1M.d.cts +103 -0
  29. package/dist/types-DaH2Sc1M.d.ts +103 -0
  30. package/package.json +23 -17
  31. package/src/components/Mutation.tsx +93 -227
  32. package/src/components/MutationKey.tsx +48 -0
  33. package/src/components/Query.tsx +93 -259
  34. package/src/components/QueryKey.tsx +73 -0
  35. package/src/components/QueryOptions.tsx +54 -177
  36. package/src/components/index.ts +2 -0
  37. package/src/generators/__snapshots__/clientDataReturnTypeFull.ts +43 -0
  38. package/src/generators/__snapshots__/clientGetImportPath.ts +43 -0
  39. package/src/generators/__snapshots__/clientPostImportPath.ts +32 -0
  40. package/src/generators/__snapshots__/findByTags.ts +43 -0
  41. package/src/generators/__snapshots__/findByTagsPathParamsObject.ts +43 -0
  42. package/src/generators/__snapshots__/findByTagsWithZod.ts +43 -0
  43. package/src/generators/__snapshots__/getAsMutation.ts +34 -0
  44. package/src/generators/__snapshots__/postAsQuery.ts +41 -0
  45. package/src/generators/__snapshots__/updatePetById.ts +32 -0
  46. package/src/generators/__snapshots__/updatePetByIdPathParamsObject.ts +36 -0
  47. package/src/generators/index.ts +2 -0
  48. package/src/generators/mutationGenerator.tsx +109 -0
  49. package/src/generators/queryGenerator.tsx +114 -0
  50. package/src/plugin.ts +71 -52
  51. package/src/types.ts +62 -78
  52. package/dist/chunk-TGLXUPN4.cjs +0 -536
  53. package/dist/chunk-TGLXUPN4.cjs.map +0 -1
  54. package/dist/chunk-XWXMQJD6.js +0 -536
  55. package/dist/chunk-XWXMQJD6.js.map +0 -1
  56. package/dist/index-B3C-JOIU.d.cts +0 -299
  57. package/dist/index-B3C-JOIU.d.ts +0 -299
  58. package/src/OperationGenerator.tsx +0 -75
  59. package/src/components/SchemaType.tsx +0 -63
  60. package/src/components/__snapshots__/Mutation/Pets.ts +0 -46
  61. package/src/components/__snapshots__/Query/showPetById.ts +0 -59
@@ -1,252 +1,118 @@
1
- import transformers from '@kubb/core/transformers'
2
- import { FunctionParams, URLPath } from '@kubb/core/utils'
3
- import { File, Function, useApp } from '@kubb/react'
4
- import { pluginTsName } from '@kubb/plugin-ts'
5
- import { useOperation, useOperationManager } from '@kubb/plugin-oas/hooks'
6
- import { getASTParams, getComments } from '@kubb/plugin-oas/utils'
1
+ import { URLPath } from '@kubb/core/utils'
2
+ import { File, Function, FunctionParams } from '@kubb/react'
7
3
 
8
- import { SchemaType } from './SchemaType.tsx'
9
-
10
- import type { HttpMethod } from '@kubb/oas'
4
+ import { type Operation, isOptional } from '@kubb/oas'
5
+ import { Client } from '@kubb/plugin-client/components'
6
+ import type { OperationSchemas } from '@kubb/plugin-oas'
7
+ import { getComments, getPathParams } from '@kubb/plugin-oas/utils'
11
8
  import type { ReactNode } from 'react'
12
- import type { FileMeta, PluginSwr } from '../types.ts'
9
+ import type { PluginSwr } from '../types.ts'
10
+ import { MutationKey } from './MutationKey.tsx'
13
11
 
14
- type TemplateProps = {
12
+ type Props = {
15
13
  /**
16
14
  * Name of the function
17
15
  */
18
16
  name: string
19
- /**
20
- * Parameters/options/props that need to be used
21
- */
22
- params: string
23
- /**
24
- * Generics that needs to be added for TypeScript
25
- */
26
- generics?: string
27
- /**
28
- * ReturnType(see async for adding Promise type)
29
- */
30
- returnType?: string
31
- /**
32
- * Options for JSdocs
33
- */
34
- JSDoc?: {
35
- comments: string[]
36
- }
37
- hook: {
38
- name: string
39
- generics?: string
40
- }
41
- client: {
42
- method: HttpMethod
43
- generics: string
44
- withQueryParams: boolean
45
- withPathParams: boolean
46
- withData: boolean
47
- withHeaders: boolean
48
- path: URLPath
49
- }
50
- dataReturnType: NonNullable<PluginSwr['options']['dataReturnType']>
51
- }
52
-
53
- function Template({ name, generics, returnType, params, JSDoc, client, hook, dataReturnType }: TemplateProps): ReactNode {
54
- const clientOptions = [
55
- `method: "${client.method}"`,
56
- 'url',
57
- client.withQueryParams ? 'params' : undefined,
58
- client.withData ? 'data' : undefined,
59
- client.withHeaders ? 'headers: { ...headers, ...clientOptions.headers }' : undefined,
60
- '...clientOptions',
61
- ].filter(Boolean)
62
-
63
- const resolvedClientOptions = `${transformers.createIndent(4)}${clientOptions.join(`,\n${transformers.createIndent(4)}`)}`
64
- if (client.withQueryParams) {
65
- return (
66
- <File.Source name={name} isExportable isIndexable>
67
- <Function export name={name} generics={generics} returnType={returnType} params={params} JSDoc={JSDoc}>
68
- {`
69
- const { mutation: mutationOptions, client: clientOptions = {}, shouldFetch = true } = options ?? {}
70
-
71
- const url = ${client.path.template} as const
72
- return ${hook.name}<${hook.generics}>(
73
- shouldFetch ? [url, params]: null,
74
- async (_url${client.withData ? ', { arg: data }' : ''}) => {
75
- const res = await client<${client.generics}>({
76
- ${resolvedClientOptions}
77
- })
78
-
79
- return ${dataReturnType === 'data' ? 'res.data' : 'res'}
80
- },
81
- mutationOptions
82
- )
83
- `}
84
- </Function>
85
- </File.Source>
86
- )
87
- }
88
-
89
- return (
90
- <File.Source name={name} isExportable isIndexable>
91
- <Function export name={name} generics={generics} returnType={returnType} params={params} JSDoc={JSDoc}>
92
- {`
93
- const { mutation: mutationOptions, client: clientOptions = {}, shouldFetch = true } = options ?? {}
94
-
95
- const url = ${client.path.template} as const
96
- return ${hook.name}<${hook.generics}>(
97
- shouldFetch ? url : null,
98
- async (_url${client.withData ? ', { arg: data }' : ''}) => {
99
- const res = await client<${client.generics}>({
100
- ${resolvedClientOptions}
101
- })
102
-
103
- return ${dataReturnType === 'data' ? 'res.data' : 'res'}
104
- },
105
- mutationOptions
106
- )
107
- `}
108
- </Function>
109
- </File.Source>
110
- )
17
+ typeName: string
18
+ clientName: string
19
+ mutationKeyName: string
20
+ mutationKeyTypeName: string
21
+ typeSchemas: OperationSchemas
22
+ operation: Operation
23
+ dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
24
+ pathParamsType: PluginSwr['resolvedOptions']['pathParamsType']
111
25
  }
112
26
 
113
- const defaultTemplates = {
114
- default: Template,
115
- } as const
116
-
117
- type Props = {
118
- factory: {
119
- name: string
120
- }
121
- /**
122
- * This will make it possible to override the default behaviour.
123
- */
124
- Template?: React.ComponentType<TemplateProps>
27
+ type GetParamsProps = {
28
+ pathParamsType: PluginSwr['resolvedOptions']['pathParamsType']
29
+ dataReturnType: PluginSwr['resolvedOptions']['client']['dataReturnType']
30
+ typeSchemas: OperationSchemas
31
+ mutationKeyTypeName: string
125
32
  }
126
33
 
127
- export function Mutation({ factory, Template = defaultTemplates.default }: Props): ReactNode {
128
- const {
129
- plugin: {
130
- options: { dataReturnType },
131
- },
132
- } = useApp<PluginSwr>()
133
- const { getSchemas, getName } = useOperationManager()
134
- const operation = useOperation()
135
-
136
- const name = getName(operation, { type: 'function' })
137
- const schemas = getSchemas(operation, { pluginKey: [pluginTsName], type: 'type' })
138
-
139
- const params = new FunctionParams()
140
- const client = {
141
- method: operation.method,
142
- path: new URLPath(operation.path),
143
- generics: [`${factory.name}["data"]`, `${factory.name}["error"]`, schemas.request?.name ? `${factory.name}["request"]` : ''].filter(Boolean).join(', '),
144
- withQueryParams: !!schemas.queryParams?.name,
145
- withData: !!schemas.request?.name,
146
- withPathParams: !!schemas.pathParams?.name,
147
- withHeaders: !!schemas.headerParams?.name,
148
- }
149
-
150
- const resultGenerics = [`${factory.name}["response"]`, `${factory.name}["error"]`]
34
+ function getParams({ pathParamsType, dataReturnType, typeSchemas, mutationKeyTypeName }: GetParamsProps) {
35
+ const TData = dataReturnType === 'data' ? typeSchemas.response.name : `ResponseConfig<${typeSchemas.response.name}>`
151
36
 
152
- params.add([
153
- ...getASTParams(schemas.pathParams, { typed: true }),
154
- {
155
- name: 'params',
156
- type: `${factory.name}['queryParams']`,
157
- enabled: client.withQueryParams,
158
- required: false,
37
+ return FunctionParams.factory({
38
+ pathParams: {
39
+ mode: pathParamsType === 'object' ? 'object' : 'inlineSpread',
40
+ children: getPathParams(typeSchemas.pathParams, { typed: true }),
159
41
  },
160
- {
161
- name: 'headers',
162
- type: `${factory.name}['headerParams']`,
163
- enabled: client.withHeaders,
164
- required: false,
165
- },
166
- {
167
- name: 'options',
168
- required: false,
169
- type: `{
170
- mutation?: SWRMutationConfiguration<${resultGenerics.join(', ')}>,
171
- client?: ${factory.name}['client']['parameters'],
172
- shouldFetch?: boolean,
173
- }`,
42
+ params: typeSchemas.queryParams?.name
43
+ ? {
44
+ type: typeSchemas.queryParams?.name,
45
+ optional: isOptional(typeSchemas.queryParams?.schema),
46
+ }
47
+ : undefined,
48
+ headers: typeSchemas.headerParams?.name
49
+ ? {
50
+ type: typeSchemas.headerParams?.name,
51
+ optional: isOptional(typeSchemas.headerParams?.schema),
52
+ }
53
+ : undefined,
54
+ options: {
55
+ type: `
56
+ {
57
+ mutation?: Parameters<typeof useSWRMutation<${[TData, typeSchemas.errors?.map((item) => item.name).join(' | ') || 'Error', mutationKeyTypeName, typeSchemas.request?.name].join(', ')}>>[2],
58
+ client?: ${typeSchemas.request?.name ? `Partial<RequestConfig<${typeSchemas.request?.name}>>` : 'Partial<RequestConfig>'},
59
+ shouldFetch?: boolean,
60
+ }
61
+ `,
174
62
  default: '{}',
175
63
  },
176
- ])
177
-
178
- const hook = {
179
- name: 'useSWRMutation',
180
- generics: [...resultGenerics, client.withQueryParams ? '[typeof url, typeof params] | null' : 'typeof url | null'].join(', '),
181
- }
182
-
183
- return (
184
- <Template
185
- name={name}
186
- JSDoc={{ comments: getComments(operation) }}
187
- client={client}
188
- hook={hook}
189
- params={params.toString()}
190
- returnType={`SWRMutationResponse<${resultGenerics.join(', ')}>`}
191
- dataReturnType={dataReturnType}
192
- />
193
- )
64
+ })
194
65
  }
195
66
 
196
- type FileProps = {
197
- /**
198
- * This will make it possible to override the default behaviour.
199
- */
200
- templates?: typeof defaultTemplates
201
- }
202
-
203
- Mutation.File = function ({ templates = defaultTemplates }: FileProps): ReactNode {
204
- const {
205
- plugin: {
206
- options: {
207
- extName,
208
- client: { importPath },
209
- },
210
- },
211
- } = useApp<PluginSwr>()
67
+ export function Mutation({ name, clientName, mutationKeyName, mutationKeyTypeName, pathParamsType, dataReturnType, typeSchemas, operation }: Props): ReactNode {
68
+ const TData = dataReturnType === 'data' ? typeSchemas.response.name : `ResponseConfig<${typeSchemas.response.name}>`
69
+ const generics = [
70
+ TData,
71
+ typeSchemas.errors?.map((item) => item.name).join(' | ') || 'Error',
72
+ `${mutationKeyTypeName} | null`,
73
+ typeSchemas.request?.name,
74
+ ].filter(Boolean)
212
75
 
213
- const { getSchemas, getFile, getName } = useOperationManager()
214
- const operation = useOperation()
76
+ const mutationKeyParams = MutationKey.getParams({
77
+ pathParamsType,
78
+ typeSchemas,
79
+ })
215
80
 
216
- const schemas = getSchemas(operation, { pluginKey: [pluginTsName], type: 'type' })
217
- const file = getFile(operation)
218
- const fileType = getFile(operation, { pluginKey: [pluginTsName] })
219
- const factoryName = getName(operation, { type: 'type' })
81
+ const params = getParams({
82
+ pathParamsType,
83
+ dataReturnType,
84
+ typeSchemas,
85
+ mutationKeyTypeName,
86
+ })
220
87
 
221
- const Template = templates.default
222
- const factory = {
223
- name: factoryName,
224
- }
88
+ const clientParams = Client.getParams({
89
+ typeSchemas,
90
+ pathParamsType,
91
+ })
225
92
 
226
93
  return (
227
- <File<FileMeta> baseName={file.baseName} path={file.path} meta={file.meta}>
228
- <File.Import name="useSWRMutation" path="swr/mutation" />
229
- <File.Import name={['SWRMutationConfiguration', 'SWRMutationResponse']} path="swr/mutation" isTypeOnly />
230
- <File.Import name={'client'} path={importPath} />
231
- <File.Import name={['ResponseConfig']} path={importPath} isTypeOnly />
232
- <File.Import
233
- name={[
234
- schemas.request?.name,
235
- schemas.response.name,
236
- schemas.pathParams?.name,
237
- schemas.queryParams?.name,
238
- schemas.headerParams?.name,
239
- ...(schemas.errors?.map((error) => error.name) || []),
240
- ].filter(Boolean)}
241
- root={file.path}
242
- path={fileType.path}
243
- isTypeOnly
244
- />
94
+ <File.Source name={name} isExportable isIndexable>
95
+ <Function
96
+ name={name}
97
+ export
98
+ params={params.toConstructor()}
99
+ JSDoc={{
100
+ comments: getComments(operation),
101
+ }}
102
+ >
103
+ {`
104
+ const { mutation: mutationOptions, client: config = {}, shouldFetch = true } = options ?? {}
105
+ const mutationKey = ${mutationKeyName}(${mutationKeyParams.toCall()})
245
106
 
246
- <SchemaType factory={factory} />
247
- <Mutation Template={Template} factory={factory} />
248
- </File>
107
+ return useSWRMutation<${generics}>(
108
+ shouldFetch ? mutationKey : null,
109
+ async (_url${typeSchemas.request?.name ? ', { arg: data }' : ''}) => {
110
+ return ${clientName}(${clientParams.toCall()})
111
+ },
112
+ mutationOptions
113
+ )
114
+ `}
115
+ </Function>
116
+ </File.Source>
249
117
  )
250
118
  }
251
-
252
- Mutation.templates = defaultTemplates
@@ -0,0 +1,48 @@
1
+ import { URLPath } from '@kubb/core/utils'
2
+ import { File, Function, FunctionParams, Type } from '@kubb/react'
3
+
4
+ import type { Operation } from '@kubb/oas'
5
+ import type { OperationSchemas } from '@kubb/plugin-oas'
6
+ import type { ReactNode } from 'react'
7
+ import type { PluginSwr } from '../types'
8
+
9
+ type Props = {
10
+ name: string
11
+ typeName: string
12
+ typeSchemas: OperationSchemas
13
+ operation: Operation
14
+ pathParamsType: PluginSwr['resolvedOptions']['pathParamsType']
15
+ keysFn: ((keys: unknown[]) => unknown[]) | undefined
16
+ }
17
+
18
+ type GetParamsProps = {
19
+ pathParamsType: PluginSwr['resolvedOptions']['pathParamsType']
20
+ typeSchemas: OperationSchemas
21
+ }
22
+
23
+ function getParams({}: GetParamsProps) {
24
+ return FunctionParams.factory({})
25
+ }
26
+
27
+ export function MutationKey({ name, typeSchemas, pathParamsType, operation, typeName, keysFn = (name) => name }: Props): ReactNode {
28
+ const path = new URLPath(operation.path)
29
+ const params = getParams({ pathParamsType, typeSchemas })
30
+ const keys = [JSON.stringify({ url: path.path })].filter(Boolean)
31
+
32
+ return (
33
+ <>
34
+ <File.Source name={name} isExportable isIndexable>
35
+ <Function.Arrow name={name} export params={params.toConstructor()} singleLine>
36
+ {`[${keysFn(keys).join(', ')}] as const`}
37
+ </Function.Arrow>
38
+ </File.Source>
39
+ <File.Source name={typeName} isExportable isIndexable isTypeOnly>
40
+ <Type name={typeName} export>
41
+ {`ReturnType<typeof ${name}>`}
42
+ </Type>
43
+ </File.Source>
44
+ </>
45
+ )
46
+ }
47
+
48
+ MutationKey.getParams = getParams