Skip to content

Commit

Permalink
feat: QueryKeyFunction to render queryKey with React(`@kubb/react-t…
Browse files Browse the repository at this point in the history
…emplate`)
  • Loading branch information
stijnvanhulle committed Oct 9, 2023
1 parent 09a1b34 commit 0157491
Show file tree
Hide file tree
Showing 15 changed files with 181 additions and 60 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/utils/URLPath.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { camelCase, camelCaseTransformMerge } from 'change-case'

type URLObject = {
export type URLObject = {
url: string
params?: Record<string, string>
}
Expand Down
13 changes: 13 additions & 0 deletions packages/react-template/src/components/Function.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ describe('<Function/>', () => {
`),
)
})

test('render ArrowFunction SingleLine', async () => {
const Component = () => {
return (
<Function.Arrow name="getData" export async generics={['TData']} singleLine returnType="number">
2;
</Function.Arrow>
)
}
const { output } = render(<Component />)

expect(await format(output)).toMatch(await format(`export const getData = async <TData>(): Promise<number> => 2;`))
})
// test('render Function ServerComponent(beta)', async () => {
// const Component = async () => {
// const data = await Promise.resolve('return 2;')
Expand Down
37 changes: 31 additions & 6 deletions packages/react-template/src/components/Function.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,21 @@ export function Function({ name, export: canExport, async, generics, params, ret
)
}

export function ArrowFunction({ name, export: canExport, async, generics, params, returnType, JSDoc, children }: Props): React.ReactNode {
type ArrowFunctionProps = Props & {
singleLine?: boolean
}

export function ArrowFunction({
name,
export: canExport,
async,
generics,
params,
returnType,
JSDoc,
singleLine,
children,
}: ArrowFunctionProps): React.ReactNode {
return (
<>
{JSDoc?.comments && (
Expand Down Expand Up @@ -84,11 +98,22 @@ export function ArrowFunction({ name, export: canExport, async, generics, params
{'>'}
</Text>
)}
<Text>{' => {'}</Text>
<br />
<Text indentSize={4}>{children}</Text>
<br />
<Text>{'};'}</Text>
{singleLine && (
<>
<Text>{' => '}</Text>
<Text indentSize={4}>{children}</Text>
</>
)}

{!singleLine && (
<>
<Text>{' => {'}</Text>
<br />
<Text indentSize={4}>{children}</Text>
<br />
<Text>{'};'}</Text>
</>
)}
</>
)
}
Expand Down
11 changes: 3 additions & 8 deletions packages/swagger-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@
"@kubb/swagger": "workspace:*",
"@kubb/swagger-ts": "workspace:*",
"@kubb/ts-codegen": "workspace:*",
"change-case": "^4.1.2"
"change-case": "^4.1.2",
"react": "^18.2.0"
},
"devDependencies": {
"@kubb/eslint-config": "workspace:*",
Expand All @@ -93,13 +94,7 @@
"typescript": "^5.2.2"
},
"peerDependencies": {
"axios": "^1.4.0",
"react": "^18.2.0"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
"axios": "^1.4.0"
},
"packageManager": "[email protected]",
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion packages/swagger-client/src/builders/ClientBuilder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class ClientBuilder extends OasBuilder<Config> {
params={params}
returnType={dataReturnType === 'data' ? `ResponseConfig<${clientGenerics[0]}>["data"]` : `ResponseConfig<${clientGenerics[0]}>`}
method={method}
url={new URLPath(operation.path).template}
path={new URLPath(operation.path)}
withParams={!!schemas.queryParams?.name}
withData={!!schemas.request?.name}
withHeaders={!!schemas.headerParams?.name}
Expand Down
35 changes: 22 additions & 13 deletions packages/swagger-client/src/components/ClientFunction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,27 @@ import React from 'react'

import { createIndent, Function } from '@kubb/react-template'

import type { URLPath } from '@kubb/core'
import type { HttpMethod } from '@kubb/swagger'
import type { ReactNode } from 'react'
import type { Options as PluginOptions } from '../types'

type Props = {
name: string
params: string
generics: string[]
returnType: string
params: string
comments: string[]
children?: ReactNode

// props Client
method: HttpMethod
url: string
path: URLPath
clientGenerics: string[]
dataReturnType: PluginOptions['dataReturnType']
withParams?: boolean
withData?: boolean
withHeaders?: boolean
comments: string[]
children?: ReactNode
}

export function ClientFunction({
Expand All @@ -28,7 +31,7 @@ export function ClientFunction({
returnType,
params,
method,
url,
path,
clientGenerics,
withParams,
withData,
Expand All @@ -39,7 +42,7 @@ export function ClientFunction({
}: Props): React.ReactNode {
const clientParams = [
`method: "${method}"`,
`url: ${url}`,
`url: ${path.template}`,
withParams ? 'params' : undefined,
withData ? 'data' : undefined,
withHeaders ? 'headers: { ...headers, ...options.headers }' : undefined,
Expand All @@ -48,21 +51,27 @@ export function ClientFunction({

const clientOptions = `${createIndent(4)}${clientParams.join(`,\n${createIndent(4)}`)}`

if (dataReturnType === 'full') {
return (
<Function name={name} async export generics={generics} returnType={returnType} params={params} JSDoc={{ comments }}>
{`
return client<${clientGenerics.join(', ')}>({
${createIndent(4)}${clientParams.join(`,\n${createIndent(4)}`)}
});`}
{children}
</Function>
)
}

return (
<Function name={name} async export generics={generics} returnType={returnType} params={params} JSDoc={{ comments }}>
{dataReturnType === 'data' &&
`
{`
const { data: resData } = await client<${clientGenerics.join(', ')}>({
${clientOptions}
});
return resData;`}

{dataReturnType === 'full' &&
`
return client<${clientGenerics.join(', ')}>({
${createIndent(4)}${clientParams.join(`,\n${createIndent(4)}`)}
});`}
{children}
</Function>
)
Expand Down
5 changes: 4 additions & 1 deletion packages/swagger-tanstack-query/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,15 @@
"@kubb/swagger-client": "workspace:*",
"@kubb/swagger-ts": "workspace:*",
"@kubb/ts-codegen": "workspace:*",
"change-case": "^4.1.2"
"change-case": "^4.1.2",
"@kubb/react-template": "workspace:*",
"react": "^18.2.0"
},
"devDependencies": {
"@kubb/eslint-config": "workspace:*",
"@kubb/ts-config": "workspace:*",
"@kubb/tsup-config": "workspace:*",
"@types/react": "^18.2.25",
"eslint": "^8.51.0",
"tsup": "^7.2.0",
"typescript": "^5.2.2"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
/* eslint- @typescript-eslint/explicit-module-boundary-types */
import { combineCodes, createFunctionParams, createJSDocBlockText, URLPath } from '@kubb/core'
import { render } from '@kubb/react-template'
import { getComments, getDataParams, getParams, OasBuilder } from '@kubb/swagger'

import { camelCase, pascalCase } from 'change-case'

import { QueryKeyFunction } from '../components/index.ts'

import type { Import } from '@kubb/core'
import type { Operation, OperationSchemas, Resolver } from '@kubb/swagger'
import type { Options as PluginOptions } from '../types'
import type { Framework, FrameworkImports } from '../types.ts'
import type { Framework, FrameworkImports, Options as PluginOptions } from '../types.ts'

type BaseConfig = {
dataReturnType: PluginOptions['dataReturnType']
Expand All @@ -27,16 +29,15 @@ type QueryConfig = BaseConfig & {
type MutationConfig = BaseConfig
type Config = QueryConfig | MutationConfig

type QueryResult = { code: string; name: string }
type QueryResult = { code: string; name: string; imports: Import[] }

export class QueryBuilder extends OasBuilder<Config> {
private get queryKey(): QueryResult {
const { operation, schemas, framework } = this.config
const codes: string[] = []

const name = camelCase(`${operation.getOperationId()}QueryKey`)

const paramsData = [
const params = createFunctionParams([
...getDataParams(schemas.pathParams, {
typed: true,
override: framework === 'vue' ? (item) => ({ ...item, type: `MaybeRef<${item.type}>` }) : undefined,
Expand All @@ -47,21 +48,22 @@ export class QueryBuilder extends OasBuilder<Config> {
enabled: !!schemas.queryParams?.name,
required: !!schemas.queryParams?.schema.required?.length,
},
]
const params = createFunctionParams(paramsData)
])

const result = [
new URLPath(operation.path).toObject({
type: 'template',
stringify: true,
replacer: framework === 'vue' ? (pathParam) => `unref(${pathParam})` : undefined,
}),
schemas.queryParams?.name ? `...(params ? [params] : [])` : undefined,
].filter(Boolean)
const FrameworkComponent = QueryKeyFunction[framework]

const Component = () => {
return (
<>
<FrameworkComponent name={name} params={params} path={new URLPath(operation.path)} withParams={!!schemas.queryParams?.name} />
</>
)
}
const { output, imports } = render(<Component />)

codes.push(`export const ${name} = (${params}) => [${result.join(',')}] as const;`)
codes.push(output)

return { code: combineCodes(codes), name }
return { code: combineCodes(codes), name, imports }
}

private get queryOptions(): QueryResult {
Expand Down Expand Up @@ -142,7 +144,7 @@ export function ${name} <${generics.join(', ')}>(${params}): ${frameworkImports.
};
`)

return { code: combineCodes(codes), name }
return { code: combineCodes(codes), name, imports: [] }
}

private get query(): QueryResult {
Expand Down Expand Up @@ -229,7 +231,7 @@ export function ${name} <${generics.join(',')}>(${params}): ${frameworkImports.q
};
`)

return { code: combineCodes(codes), name }
return { code: combineCodes(codes), name, imports: [] }
}

//infinite
Expand Down Expand Up @@ -319,7 +321,7 @@ export function ${name} <${generics.join(', ')}>(${params}): ${frameworkImports.
};
`)

return { code: combineCodes(codes), name }
return { code: combineCodes(codes), name, imports: [] }
}

private get queryInfinite(): QueryResult {
Expand Down Expand Up @@ -408,7 +410,7 @@ export function ${name} <${generics.join(',')}>(${params}): ${frameworkImports.q
};
`)

return { code: combineCodes(codes), name }
return { code: combineCodes(codes), name, imports: [] }
}

private get mutation(): QueryResult {
Expand Down Expand Up @@ -492,7 +494,7 @@ export function ${name} <${generics.join(',')}>(${params}): ${frameworkImports.m
};
`)

return { code: combineCodes(codes), name }
return { code: combineCodes(codes), name, imports: [] }
}

configure(config: Config): this {
Expand Down Expand Up @@ -532,7 +534,7 @@ export function ${name} <${generics.join(',')}>(${params}): ${frameworkImports.m
return codes.join('\n')
}

imports(type: 'query' | 'mutation'): Import[] {
return []
imports(): Import[] {
return [...this.queryKey.imports]
}
}
2 changes: 1 addition & 1 deletion packages/swagger-tanstack-query/src/builders/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './QueryBuilder.ts'
export * from './QueryBuilder.tsx'
Loading

0 comments on commit 0157491

Please sign in to comment.