import { URLPath } from '@kubb/core/utils' import { isOptional, type Operation } from '@kubb/oas' import type { OperationSchemas } from '@kubb/plugin-oas' import { getPathParams } from '@kubb/plugin-oas/utils' import { File, Function, FunctionParams, Type } from '@kubb/react-fabric' import type { KubbNode } from '@kubb/react-fabric/types' import type { PluginSvelteQuery, Transformer } from '../types' type Props = { name: string typeName: string typeSchemas: OperationSchemas operation: Operation paramsCasing: PluginSvelteQuery['resolvedOptions']['paramsCasing'] pathParamsType: PluginSvelteQuery['resolvedOptions']['pathParamsType'] transformer: Transformer | undefined } type GetParamsProps = { paramsCasing: PluginSvelteQuery['resolvedOptions']['paramsCasing'] pathParamsType: PluginSvelteQuery['resolvedOptions']['pathParamsType'] typeSchemas: OperationSchemas } function getParams({ pathParamsType, paramsCasing, typeSchemas }: GetParamsProps) { return FunctionParams.factory({ pathParams: { mode: pathParamsType === 'object' ? 'object' : 'inlineSpread', children: getPathParams(typeSchemas.pathParams, { typed: true, casing: paramsCasing }), }, data: typeSchemas.request?.name ? { type: typeSchemas.request?.name, optional: isOptional(typeSchemas.request?.schema), } : undefined, params: typeSchemas.queryParams?.name ? { type: typeSchemas.queryParams?.name, optional: isOptional(typeSchemas.queryParams?.schema), } : undefined, }) } const getTransformer: Transformer = ({ operation, schemas, casing }) => { const path = new URLPath(operation.path, { casing }) const keys = [ path.toObject({ type: 'path', stringify: true, }), schemas.queryParams?.name ? '...(params ? [params] : [])' : undefined, schemas.request?.name ? '...(data ? [data] : [])' : undefined, ].filter(Boolean) return keys } export function QueryKey({ name, typeSchemas, paramsCasing, pathParamsType, operation, typeName, transformer = getTransformer }: Props): KubbNode { const params = getParams({ pathParamsType, paramsCasing, typeSchemas }) const keys = transformer({ operation, schemas: typeSchemas, casing: paramsCasing, }) return ( <> {`[${keys.join(', ')}] as const`} {`ReturnType`} ) } QueryKey.getParams = getParams QueryKey.getTransformer = getTransformer