Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions docs/src/content/docs/packages/typegen/emitters/tanstack-query.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<PaginatedResponseOfWorkItemSummary>;
export function useSearchWorkItems<TSelected>(input: SearchWorkItemsInput, options: {
select: (data: PaginatedResponseOfWorkItemSummary) => TSelected;
}): import('@tanstack/react-query').UseQueryResult<TSelected>;
export function useSearchWorkItems<TSelected>(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:

Expand Down
1 change: 1 addition & 0 deletions packages/ZibStack.NET.TypeGen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof {op.Name}>>";
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}<TSelected>({selectInput}options: {{ select: {selector} }}): {result}<TSelected>;");
sb.AppendLine($"export function {hookName}<TSelected>({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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type Expect<T extends true> = 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<Equal<typeof plain.data, string | undefined>>;
type Picked = Expect<Equal<typeof picked.data, number | undefined>>;
type Greeting = Expect<Equal<typeof greeting.data, string | undefined>>;
type Formatted = Expect<Equal<typeof formatted.data, { text: string } | undefined>>;
type Defaulted = Expect<Equal<typeof defaulted.data, number | undefined>>;
type Status = Expect<Equal<typeof status.data, string | undefined>>;
type Healthy = Expect<Equal<typeof healthy.data, boolean | undefined>>;
// @ts-expect-error Endpoint input is required.
useGetName({ select: (name: string) => name.length });
// @ts-expect-error A selected type requires a selector.
useGetName<number>({ 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()
{
Expand Down Expand Up @@ -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}");
Expand Down
Loading