diff --git a/docs/src/content/docs/packages/typegen/emitters/tanstack-query.md b/docs/src/content/docs/packages/typegen/emitters/tanstack-query.md index 17ee3cb..00a4c28 100644 --- a/docs/src/content/docs/packages/typegen/emitters/tanstack-query.md +++ b/docs/src/content/docs/packages/typegen/emitters/tanstack-query.md @@ -202,11 +202,36 @@ export function searchWorkItemsOptions(input: SearchWorkItemsInput) { }); } -export function useSearchWorkItems(input: SearchWorkItemsInput) { - return useQuery(searchWorkItemsOptions(input)); +export function useSearchWorkItems(input: SearchWorkItemsInput, options?: { select?: undefined }): + import('@tanstack/react-query').UseQueryResult; +export function useSearchWorkItems(input: SearchWorkItemsInput, options: { + select: (data: PaginatedResponseOfWorkItemSummary) => TSelected; +}): import('@tanstack/react-query').UseQueryResult; +export function useSearchWorkItems(input: SearchWorkItemsInput, options?: { + select?: (data: PaginatedResponseOfWorkItemSummary) => TSelected; +}) { + return useQuery({ + ...searchWorkItemsOptions(input), + select: options?.select, + }); } ``` +Every generated GET hook accepts a component-level `select` callback with the +endpoint's response type as its input. TypeScript infers `data` from the +callback's return value (`WorkItemSummary[] | undefined` here): + +```typescript +const { data: items } = useSearchWorkItems({ workspaceId, page: 1 }, { + select: response => response.items, +}); +``` + +The query cache still holds the full response, and omitting `select` returns +that response as `data`. For a hook with no endpoint inputs, pass `{ select }` +as the first argument. If all inputs are optional, pass `undefined` as the +first argument to use their defaults. No C# attributes or settings are needed. + Mutations get a fetch function, `mutationOptions`, a React hook, and tag-wide invalidation: diff --git a/packages/ZibStack.NET.TypeGen/README.md b/packages/ZibStack.NET.TypeGen/README.md index 8fea3fa..20b868d 100644 --- a/packages/ZibStack.NET.TypeGen/README.md +++ b/packages/ZibStack.NET.TypeGen/README.md @@ -55,6 +55,7 @@ the property graph, so you only annotate root aggregates. - **TanStack Query emitter** — generates React Query v5 clients from the same endpoint discovery model as OpenAPI. Supports Minimal API `.WithName(...)` / `.WithTags(...)`, custom API clients, split-by-tag output, and cache helpers. + Generated GET hooks accept a typed `select` callback for component-specific data. Set `q.PreserveBaseUrlPath = true` to retain reverse-proxy service prefixes. See the [URL resolution guide](https://mistykuu.github.io/ZibStack.NET/packages/typegen/emitters/tanstack-query/#reverse-proxy-service-prefixes). - **Fluent project-wide config** via `ITypeGenConfigurator` — global output dir, diff --git a/packages/ZibStack.NET.TypeGen/src/ZibStack.NET.TypeGen/Emitters/TanStackQueryEmitter.cs b/packages/ZibStack.NET.TypeGen/src/ZibStack.NET.TypeGen/Emitters/TanStackQueryEmitter.cs index 8734c26..18d13e9 100644 --- a/packages/ZibStack.NET.TypeGen/src/ZibStack.NET.TypeGen/Emitters/TanStackQueryEmitter.cs +++ b/packages/ZibStack.NET.TypeGen/src/ZibStack.NET.TypeGen/Emitters/TanStackQueryEmitter.cs @@ -788,23 +788,34 @@ private static void EmitHook(StringBuilder sb, OperationModel op, TanStackQueryS var hookName = "use" + ToPascalIdentifier(op.Name); if (op.IsQuery) { - sb.Append($"export function {hookName}("); + var response = $"Awaited>"; + const string result = "import('@tanstack/react-query').UseQueryResult"; + var plainInput = ""; + var selectInput = ""; + var implementationInput = ""; if (op.HasInput) - sb.Append(op.HasRequiredInput ? $"input: {op.InputTypeName}" : $"input: {op.InputTypeName} = {{}}"); - sb.AppendLine(") {"); + { + plainInput = $"input{(op.HasRequiredInput ? "" : "?")}: {op.InputTypeName}, "; + selectInput = $"input: {op.InputTypeName}{(op.HasRequiredInput ? "" : " | undefined")}, "; + implementationInput = $"input: {op.InputTypeName}{(op.HasRequiredInput ? "" : " = {}")}, "; + } + // A caller may specify a selected type only when supplying a selector. + var selector = $"(data: {response}) => TSelected"; + sb.AppendLine($"export function {hookName}({plainInput}options?: {{ select?: undefined }}): {result}<{response}>;"); + sb.AppendLine($"export function {hookName}({selectInput}options: {{ select: {selector} }}): {result};"); + sb.AppendLine($"export function {hookName}({implementationInput}options?: {{ select?: {selector} }}) {{"); + sb.AppendLine(" return useQuery({"); if (query.EmitQueryOptions) - sb.AppendLine(op.HasInput - ? $" return useQuery({op.Name}Options(input));" - : $" return useQuery({op.Name}Options());"); + sb.AppendLine($" ...{op.Name}Options({(op.HasInput ? "input" : "")}),"); else { var keyCall = BuildKeyCall(op); var fetchCall = op.HasInput ? $"{op.Name}(input, signal)" : $"{op.Name}(signal)"; - sb.AppendLine(" return useQuery({"); sb.AppendLine($" queryKey: {keyCall},"); sb.AppendLine($" queryFn: ({{ signal }}) => {fetchCall},"); - sb.AppendLine(" });"); } + sb.AppendLine(" select: options?.select,"); + sb.AppendLine(" });"); sb.AppendLine("}"); sb.AppendLine(); return; diff --git a/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/TanStackQueryEmitterTests.cs b/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/TanStackQueryEmitterTests.cs index 6d840f6..07e34da 100644 --- a/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/TanStackQueryEmitterTests.cs +++ b/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/TanStackQueryEmitterTests.cs @@ -103,7 +103,7 @@ public void ComplexEndpoint_EmitsTypedQueryAndMutationSurface() Assert.Contains("minimumBudget: input.minimumBudget", ts); Assert.Contains("pageSize: input.pageSize", ts); Assert.Contains("export function getWorkspaceReportJobsOptions(input: GetWorkspaceReportJobsInput)", ts); - Assert.Contains("return useQuery(getWorkspaceReportJobsOptions(input));", ts); + Assert.Contains("...getWorkspaceReportJobsOptions(input),", ts); Assert.Contains("export function prefetchGetWorkspaceReportJobs(queryClient: QueryClient, input: GetWorkspaceReportJobsInput)", ts); Assert.Contains("export function invalidateReportsQueries(queryClient: QueryClient)", ts); diff --git a/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/ZodCompilationTests.cs b/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/ZodCompilationTests.cs index b94f9cd..e3114e2 100644 --- a/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/ZodCompilationTests.cs +++ b/packages/ZibStack.NET.TypeGen/tests/ZibStack.NET.TypeGen.Tests/ZodCompilationTests.cs @@ -281,6 +281,66 @@ public async Task TanStackPayloadValidation_CompilesWithGeneratedSchemas() $"tsc failed (exit {exitCode}):{Environment.NewLine}{stdout}{Environment.NewLine}{stderr}"); } + [Fact] + public async Task TanStackQuerySelectors_InferDataWithAndWithoutOptionsFactories() + { + if (_skip) return; + + var model = new SchemaModel(); + model.Endpoints.Add(new EndpointInfo + { + Verb = "get", Pattern = "/names/{id}", OperationId = "getName", ResponseCSharpType = "string", + Parameters = { new EndpointParameter { Name = "id", Location = ParamLocation.Route, CSharpType = "int", Required = true } }, + }); + model.Endpoints.Add(new EndpointInfo + { + Verb = "get", Pattern = "/greeting", OperationId = "getGreeting", ResponseCSharpType = "string", + Parameters = { new EndpointParameter { Name = "lang", Location = ParamLocation.Query, CSharpType = "string" } }, + }); + model.Endpoints.Add(new EndpointInfo + { + Verb = "get", Pattern = "/status", OperationId = "getStatus", ResponseCSharpType = "string", + }); + + await PrepareWorkspaceAsync("@tanstack/react-query@5.90.21", "react@19.1.0", "@types/react@19.1.0"); + foreach (var emitQueryOptions in new[] { true, false }) + { + var settings = new GlobalSettings(); + settings.TanStackQuery.EmitQueryOptions = emitQueryOptions; + settings.TanStackQuery.BaseUrlExpression = "undefined"; + var client = Assert.Single(TanStackQueryEmitter.Emit(model, settings)); + File.WriteAllText(Path.Combine(_tempDir, emitQueryOptions ? "with-options.ts" : "without-options.ts"), client.Content + "\n" + """ + type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; + type Expect = T; + const plain = useGetName({ id: 1 }); + const picked = useGetName({ id: 1 }, { select: name => name.length }); + const greeting = useGetGreeting(); + const formatted = useGetGreeting({ lang: 'en' }, { select: text => ({ text }) }); + const defaulted = useGetGreeting(undefined, { select: text => text.length }); + const status = useGetStatus(); + const healthy = useGetStatus({ select: text => text === 'ok' }); + type Plain = Expect>; + type Picked = Expect>; + type Greeting = Expect>; + type Formatted = Expect>; + type Defaulted = Expect>; + type Status = Expect>; + type Healthy = Expect>; + // @ts-expect-error Endpoint input is required. + useGetName({ select: (name: string) => name.length }); + // @ts-expect-error A selected type requires a selector. + useGetName({ id: 1 }); + // @ts-expect-error The selector receives the endpoint response type. + useGetStatus({ select: (status: number) => status }); + """); + } + + var (exitCode, stdout, stderr) = await RunAsync("npx", + $"-y -p {TscPackageSpec} tsc --noEmit --strict --skipLibCheck --target ES2020 --moduleResolution node with-options.ts without-options.ts", + workingDir: _tempDir); + Assert.True(exitCode == 0, $"tsc failed (exit {exitCode}):\n{stdout}\n{stderr}"); + } + [Fact] public async Task ExternalZodGeoJsonSchema_CompilesAndInfersPropertyType() { @@ -392,11 +452,10 @@ public async Task CompoundOverride_WithGeneratedReferences_CompilesInSingleFile( private async Task PrepareWorkspaceAsync(params string[] additionalPackages) { - // Install zod locally so the emitted `import { z } from 'zod';` resolves. - // Node resolution walks up from temp dir; a sibling node_modules is enough. + // Keep dependencies in this fixture even if npm finds a package in a parent directory. var packages = string.Join(" ", new[] { ZodPackageSpec }.Concat(additionalPackages)); var (code, _, err) = await RunAsync("npx", - $"-y -p npm@10 npm install --silent --no-audit --no-fund --no-package-lock {packages}", + $"-y -p npm@10 npm install --prefix . --silent --no-audit --no-fund --no-package-lock {packages}", workingDir: _tempDir); if (code != 0) throw new InvalidOperationException($"zod install failed (exit {code}): {err}");