From 3114d20d68a2e512f859e0a7b7f6abcdeca55ebf Mon Sep 17 00:00:00 2001 From: Paul DeVito Date: Mon, 2 Nov 2026 00:31:39 +0200 Subject: [PATCH] refactor(examples): remove search from the workshop and venue lists The workshop and venue lists now have one query path for text: QueryKit filters. The search parameter, its max length, and its LikePattern code are gone from the parameters DTOs, the handlers, and the HTTP and MCP entrypoints. The MCP filters description of list_workshops tells a caller how to write text with a quote, in the words of new-feature.cs. The SPA keeps its search box, its search URL param, and the text box of the venue picker. The list hooks send the text as a title or name filter with containsText. quoteText moves from the filter builder to frontend/src/lib/querykit-text.ts, so the filter builder and the lists share one encoder. Each box takes its max length from the field that its filter matches. The list query tests find text through a filter that QueryKitText.Quote writes, and keep each guarantee: case does not matter, %, _, and \ are plain text, and NUL and a lone surrogate map to the filters parameter. LikePattern, its banned-symbol rule, and its tests stay. The docs now say that a list finds text through filters, and that LikePattern is the rule for a raw ILike. --- .agents/skills/frontend-feature/SKILL.md | 11 +++--- .../features/examples/workshops.md | 4 +-- .../recipes/examples/workshops.mjs | 4 +-- .agents/skills/writing-tests/SKILL.md | 2 +- .../Venues/Dtos/VenueParametersDto.cs | 7 +--- .../GetVenueList/GetVenueList.Http.cs | 5 ++- .../Features/GetVenueList/GetVenueList.cs | 22 ++---------- .../Workshops/Dtos/WorkshopParametersDto.cs | 7 +--- .../GetWorkshopList/GetWorkshopList.Http.cs | 5 ++- .../GetWorkshopList/GetWorkshopList.Mcp.cs | 5 ++- .../GetWorkshopList/GetWorkshopList.cs | 22 ++---------- .../openapi/FullstackTemplate.Server.json | 20 ++--------- docs/backend.md | 2 +- docs/backend/features-and-cqrs.md | 12 +++---- docs/frontend.md | 4 ++- docs/frontend/client-state.md | 2 +- docs/frontend/server-state.md | 2 +- docs/frontend/testing.md | 2 +- .../venues/clients/get-venue-list.ts | 2 +- .../generated/venues/types/get-venue-list.ts | 5 --- .../generated/venues/zod/get-venue-list.ts | 2 -- .../workshops/clients/get-workshop-list.ts | 2 +- .../workshops/types/get-workshop-list.ts | 5 --- .../workshops/zod/get-workshop-list.ts | 2 -- .../utils/querykit-converter.ts | 16 +-------- frontend/src/components/search-box.tsx | 2 +- .../examples/venues/apis/get-venue-list.ts | 4 ++- .../venues/components/venue-picker.test.tsx | 8 ++--- .../venues/components/venue-picker.tsx | 4 +-- .../workshops/apis/get-workshop-list.ts | 8 ++++- .../examples/workshops/workshop-list.test.tsx | 16 ++++++--- frontend/src/lib/querykit-text.test.ts | 24 +++++++++++++ frontend/src/lib/querykit-text.ts | 24 +++++++++++++ .../src/routes/(examples)/workshops/index.tsx | 14 ++++---- .../examples/workshops/workshops.spec.ts | 2 +- .../TextValues/NulInReadInputTests.cs | 2 -- .../Lists/ExampleListFilterSweepTests.cs | 6 ++-- .../Examples/Venues/VenueListQueryTests.cs | 30 ++++++---------- .../Workshops/WorkshopListQueryTests.cs | 34 ++++++------------- 39 files changed, 150 insertions(+), 200 deletions(-) create mode 100644 frontend/src/lib/querykit-text.test.ts create mode 100644 frontend/src/lib/querykit-text.ts diff --git a/.agents/skills/frontend-feature/SKILL.md b/.agents/skills/frontend-feature/SKILL.md index 692e086cc..b65b6abe8 100644 --- a/.agents/skills/frontend-feature/SKILL.md +++ b/.agents/skills/frontend-feature/SKILL.md @@ -40,6 +40,7 @@ The shared parts of a page below are in the app, also after the removal. Use the | The search box of a list, with the debounce, and the text that follows Back | `SearchBox` in [`components/search-box.tsx`](../../../frontend/src/components/search-box.tsx) | | The debounce of the search of a picker | `useDebouncedCallback` in [`hooks/use-debounced-callback.ts`](../../../frontend/src/hooks/use-debounced-callback.ts) | | The pager of a list, and the load of the next page of a picker | `Pager` in `components/ui/pager.tsx`, and `ComboboxLoadMore` in `components/ui/combobox.tsx` | +| The filter that a search box sends, with the quote rule of QueryKit | `containsText` in [`lib/querykit-text.ts`](../../../frontend/src/lib/querykit-text.ts) | | The limits of a field | `stringWithMaxLengthOf`, `maxLengthOf`, `minimumOf`, and `maximumOf` in [`lib/api-contract.ts`](../../../frontend/src/lib/api-contract.ts) | | A stale save, and the reload that keeps the edits | `StaleVersionAlert` and `LatestLoadedNote` in [`components/stale-version-alert.tsx`](../../../frontend/src/components/stale-version-alert.tsx), `useLoadLatest` in [`hooks/use-load-latest.ts`](../../../frontend/src/hooks/use-load-latest.ts), and `isStaleVersionError` in [`lib/problem-details.ts`](../../../frontend/src/lib/problem-details.ts) | | The cache and the next page after a delete | `leaveDeletedRecord` in [`lib/leave-deleted-record.ts`](../../../frontend/src/lib/leave-deleted-record.ts) | @@ -50,13 +51,13 @@ The shared parts of a page below are in the app, also after the removal. Use the Put the code of an area in `frontend/src/domain//`: the hooks and the keys in `apis/`, and the components in `components/`. Put the pages in the route folder of their URL, such as a new folder `frontend/src/routes/rooms/` for the URL `/rooms`. If the area already has keys, components, a builder, or an API file, add to them, and run their tests after each change. -1. **The contract.** The Server endpoints exist, and the generated client is current. Use the `backend-feature` skill for the Server and the `api-contract` skill for the client. The list endpoint takes a page number, a page size, and a search or a filter. The DTO has `allowedActions` and `version`. Each text field and number field of a request DTO has a limit in the contract, and so does the `search` query parameter (`[MaxLength]` on the handler parameter, frontend.md). Done when `src/api/generated//clients/` has a client for each call, and `maxLengthOf` and `maximumOf` do not throw for the fields of the form. +1. **The contract.** The Server endpoints exist, and the generated client is current. Use the `backend-feature` skill for the Server and the `api-contract` skill for the client. The list endpoint takes a page number, a page size, and QueryKit `filters`. It has no `search` parameter: the SPA sends the text of a search box as a filter. The DTO has `allowedActions` and `version`. Each text field and number field of a request DTO has a limit in the contract. The search box takes its limit from the field that it matches. Done when `src/api/generated//clients/` has a client for each call, and `maxLengthOf` and `maximumOf` do not throw for the fields of the form. 2. **The keys and the hooks.** Write `.keys.ts` (server-state.md, "Key factory"). Give all the params of the list to the list key. When the area has a list and a picker, give each its own key under `lists()`, because one is a `useQuery` and one a `useInfiniteQuery` and they cannot share a cache entry. Write one hook for each call: the list with `keepPreviousData` and `parsePagination`, the detail as `queryOptions`, the picker search with `useInfiniteQuery`, and one mutation for each write. Make each mutation update the cache as the table below says. Done when `pnpm lint` passes. In the key factory, put each parameter in the key whole, such as `(params: ListParams) => [...lists(), params]`. The lint fails on each other form. In the hooks, the lint finds the common forms of a value that the query function reads and the key does not have. It does not find all of them: read "Check" in server-state.md for the forms that it does not find, and check those forms in your hooks by reading them. -3. **The list page.** Read `search` and `page` from the URL with `validateSearch`. Build the schema from the generated query schemas with `.catch(undefined)`, so that a bad URL falls back to the default (frontend.md, "Routes"). If the list takes QueryKit `filters` and no `search`, write the `search` schema by hand (`z.string().optional().catch(undefined)`), and turn the text into a filter in a pure function with a unit test. Use the operator `@=*` (contains, ignore case). QueryKit has no escape in a quoted value: put text with a `"` in a raw string with one space of padding on each side (`""" text """`). Make the delimiter one quote longer than the longest run of quotes in the text, and at least three quotes long. Give the unit test a text with a `"`, and search for such a text on the stack in step 9. Show each state with an early return: loading (`role="status"`), error (`QueryError`), empty on a page after page 1 (a link to page 1), empty for a search (the search in quotes), and empty (how to add one, if the area has a create page). Use `SearchBox` for the search, and take its `maxLength` from the contract. The limit of `filters` is for the whole filter text, not for the text that the user types, so take the `maxLength` of the box from the field that the filter matches, such as `maxLengthOf(roomForCreationDtoSchema.shape.name)`. In its `onSearch`, navigate with `replace: true`, and change the URL only when it still has the search that the box started from (`base`), as the list pattern below does. Give the table `aria-label`, and give `whitespace-nowrap` to each cell that is not prose (code-style.md, "Styles"). On a phone (`useIsMobile`), drop the columns that do not wrap, and show their values under the name. A list of tenant data waits for `useMembership`: it gives `enabled: false` to the list query while the status is `loading` or `no-tenant`, and it shows a link to `/start-tenant` when the user has no tenant. Done when the page in the URL survives a reload, and Back from a detail page shows the list with its search in the box. The search uses `replace: true`, so Back does not step through the typed searches. +3. **The list page.** Read `search` and `page` from the URL with `validateSearch`. Build the `page` schema from the generated query schema with `.catch(undefined)`, so that a bad URL falls back to the default (frontend.md, "Routes"). The contract has no `search`, so write its schema by hand, with the max length of the field that the search matches (`z.string().max(searchMaxLength).optional().catch(undefined)`). In the list hook, send the text as `filters: containsText('name', params.search)`. `containsText` in `lib/querykit-text.ts` writes the filter `name @=* ` (contains, ignore case), and puts text with a `"` in a padded raw string. Do not write a second encoder. Search for a text with a `"` on the stack in step 9. Show each state with an early return: loading (`role="status"`), error (`QueryError`), empty on a page after page 1 (a link to page 1), empty for a search (the search in quotes), and empty (how to add one, if the area has a create page). Use `SearchBox` for the search, and take its `maxLength` from the contract. The limit of `filters` is for the whole filter text, not for the text that the user types, so take the `maxLength` of the box from the field that the filter matches, such as `maxLengthOf(roomForCreationDtoSchema.shape.name)`. In its `onSearch`, navigate with `replace: true`, and change the URL only when it still has the search that the box started from (`base`), as the list pattern below does. Give the table `aria-label`, and give `whitespace-nowrap` to each cell that is not prose (code-style.md, "Styles"). On a phone (`useIsMobile`), drop the columns that do not wrap, and show their values under the name. A list of tenant data waits for `useMembership`: it gives `enabled: false` to the list query while the status is `loading` or `no-tenant`, and it shows a link to `/start-tenant` when the user has no tenant. Done when the page in the URL survives a reload, and Back from a detail page shows the list with its search in the box. The search uses `replace: true`, so Back does not step through the typed searches. 4. **The detail page.** Return early for loading and error. Show the title in `PageHeading`. Show a button only for each entry of `allowedActions` (server-state.md, rule 8). An action that needs input, such as a role, asks for it in a form in the dialog. Give each option of that form its label in a `Record` too (messages.md). Give each action its label in a `Record` of the generated union, so that a new action on the Server fails the build until it has a label. Ask for a confirm in a `ResponsiveDialog` before an action that cannot be undone. Close the dialog when the user confirms: make the confirm button a `ResponsiveDialogClose` that calls the action. A dialog that is still open keeps the focus inside it, and it gives the focus back to its trigger when it closes, so a focus move while it is open has no effect. Read the JSDoc of `components/ui/responsive-dialog.tsx` for the gap under the header. After an action, move the focus to the heading. For a delete, ask first, then call `leaveDeletedRecord` in the `onSuccess` of `mutate`, as the detail pattern below does: show the toast with `Notification.success`, go to the list, and let the root layout move the focus to the heading of the list. After a failed delete, the user stays on the page, and the focus goes to the heading. Do not remove the detail in the mutation hook, because the page that is still on the screen reads it again and gets a 404. Done when a user with no permission sees no button, and, for a delete, a functional test sees one toast (count it one time, as testing.md, "Facts about this app", says), one `GET` of the record, and the focus on the heading of the list. 5. **The edit form.** The page renders the form only after the detail query has data, and only when `allowedActions` has `Update`. Otherwise it says why. The form schema takes each limit from the generated Zod schema of the request DTO (frontend.md, "Forms"). Put the `version` in `defaultValues` and in the PUT body (server-state.md, "Forms with server data"). Use `shouldFocusError: false` with `focusFirstError`. Before a save, clear the refusals. After a refusal, show it with `useServerErrors`. The mutation hook of the form sends `options: { suppressErrorToast: true }` to the generated client, because `apiClient` shows each refusal in a toast, and the form already shows it (server-state.md, "Errors"). For a stale save (a 409 with the stale-version type), keep the edits in the form, and show `StaleVersionAlert` with the name of the record. Its button calls `load` of `useLoadLatest` with a function that refetches the detail query and gives the form values of the new record. Each field that the new record changed takes the saved value, each other field keeps the edit of the user, and the focus goes to the first changed field. `LatestLoadedNote` names the fields that changed. Clear the refusals after the load, and clear the note before a save. Do not send the PUT again with the new version. After a save, show a toast with `Notification.success` and go to the detail page. Done when the component test of the stale save passes, and a functional test of a refused save sees the refusal on its field and no toast. 6. **The create form.** Do step 5 with no `version` and no stale reload. Its mutation hook also sends `suppressErrorToast`. If the entity has a `ForStaleVersion` index, show the create race in its own alert, because the text of `StaleVersionAlert` says that the record changed. A create that gets a 409 keeps the input of the user. After a save, go to the detail page of the new record. -7. **The search picker.** Build it on `Combobox` with the `items` prop, so that React Aria does not filter again what the Server filtered. Load the picked record by its ID with the detail hook. Put the pick first in the options when no loaded page has it. The text of the input after a pick is the name of the pick, so it is not a search. On a pick, put the record in the detail cache. Take the pick from the detail query also when a loaded page has it, so that a rename shows. Load the next page with `ComboboxLoadMore`. When the search fails, the empty state says so and what to do (messages.md, rules 3 and 7), not that no record matches, and the list searches again when it opens again. In a form, wrap the picker in a `Controller`, and give `field.ref` to the input. Done when component tests show that a pick from page 2 and a pick from a link show their names, that a rename of a pick from a link and of a pick from page 1 shows after the detail query reads the record again, and that a failed search shows its message and searches again on the next open. +7. **The search picker.** Build it on `Combobox` with the `items` prop, so that React Aria does not filter again what the Server filtered. Load the picked record by its ID with the detail hook. Put the pick first in the options when no loaded page has it. Send the search with `containsText`, as the list does (step 3), and take the `maxLength` of the input from the field that the search matches. The text of the input after a pick is the name of the pick, so it is not a search. On a pick, put the record in the detail cache. Take the pick from the detail query also when a loaded page has it, so that a rename shows. Load the next page with `ComboboxLoadMore`. When the search fails, the empty state says so and what to do (messages.md, rules 3 and 7), not that no record matches, and the list searches again when it opens again. In a form, wrap the picker in a `Controller`, and give `field.ref` to the input. Done when component tests show that a pick from page 2 and a pick from a link show their names, that a rename of a pick from a link and of a pick from page 1 shows after the detail query reads the record again, and that a failed search shows its message and searches again on the next open. 8. **The tests.** Use the `writing-tests` skill. Write a test for each limit of a form schema, in the component test of the form or in a unit test of the schema. Put a schema that a test imports in its own `*-schema.ts` file, because `react-refresh/only-export-components` refuses it in a component file. Write component tests for each part that the area has: the stale save of the edit form, the picker (step 7), and the search and the page of the list in the URL. Write a builder in `tests/support/builders/` and an API file in `tests/support/api/` for the area, or add to the ones that exist, then a functional spec that goes from the list to the detail and to each form of the area. Read back the list query and the PUT body with `api.last`. Done when `pnpm lint`, `pnpm test`, `pnpm build`, and `pnpm test:e2e` pass, and the new spec passes 10 times (`pnpm test:e2e --repeat-each=10`). 9. **The proof.** Add a link to the list in `components/app-sidebar.tsx`. Add a feature file and a recipe to the feature map of the `verify-fullstack-template` skill. Start the tenant as [`recipes/start-tenant.mjs`](../verify-fullstack-template/recipes/start-tenant.mjs) does, and delete it through the API at the end in a `finally` block, so that the next run starts with no tenant. Give one record a long name with no spaces. Run the recipe on a stack, then run `sweep.sh` on it. The sweep puts a 100-character value into each name and text field of each API answer (`nameKeys` in `sweep.mjs`), so a form opens with those values, and a save sends them back to the Server. A field with a limit under 100 then gets a 422, and the saved long value stays in the database for the next run. So in a recipe that saves, fill each text field of the form with a value of the recipe before the save, and compare the screen with the API answer, not with a literal. Done when the sweep prints `sweep: PASSED`, and you read each screenshot and find no text that is cut off: the sweep does not find all of it. @@ -78,11 +79,11 @@ Use these when the reference feature is not in the app. Change the names. The ru The list page, in `routes//index.tsx`: ```tsx +const searchMaxLength = maxLengthOf(roomForCreationDtoSchema.shape.name) const listSearchSchema = z.object({ - search: getRoomListQuerySearchSchema.catch(undefined), + search: z.string().max(searchMaxLength).optional().catch(undefined), page: getRoomListQueryPageNumberSchema.catch(undefined), }) -const searchMaxLength = maxLengthOf(getRoomListQuerySearchSchema.unwrap()) export const Route = createFileRoute('/rooms/')({ validateSearch: listSearchSchema, component: RoomsPage, staticData: { breadcrumb: 'Rooms' } }) diff --git a/.agents/skills/verify-fullstack-template/features/examples/workshops.md b/.agents/skills/verify-fullstack-template/features/examples/workshops.md index c9d4d250b..3c3a50c7c 100644 --- a/.agents/skills/verify-fullstack-template/features/examples/workshops.md +++ b/.agents/skills/verify-fullstack-template/features/examples/workshops.md @@ -13,7 +13,7 @@ A user with the `manage_workshops` permission adds a venue and a workshop in it, - `workshop-edit` saves a new title with the loaded version. The detail page shows the title. - `workshop-stale` refuses a save after another tab saved: the alert `This workshop changed after you opened it.` shows, and `Load the latest` loads the saved workshop into the form on the same URL. - `workshop-actions` shows one button for each entry of `allowedActions`. `Schedule` moves the workshop to `Scheduled`. `Cancel workshop` opens the dialog `Cancel this workshop?` first. -- `workshop-search` puts the search in the URL (`?search=`) and lists the workshops whose title contains it. +- `workshop-search` puts the search in the URL (`?search=`), sends it as the filter `title @=* ""`, and lists the workshops whose title contains it. ## How to get to it (user POV) @@ -38,7 +38,7 @@ Preconditions: - **Edit.** Click `Edit` in the group `Actions for `. Fill `Title`, click `Save`. `PUT /api/v1/workshops/{id}` gives 200 with a `version` that is larger than the loaded one. The detail page shows the new title. - **Stale save.** Open the edit page in this tab and in a second tab. Save a title in the second tab. Save another title in the first tab. `PUT` gives 409 with the type `urn:fullstacktemplate:problem:stale-version`. The alert shows, and `Title` keeps the text of the first tab. Click `Load the latest`. The URL stays `/workshops/<id>/edit`, and `Title` has the title of the second tab. - **Actions.** On the detail page, the buttons equal `allowedActions` of the last `GET` (`Update` is the `Edit` link). Click `Schedule`. `POST /api/v1/workshops/{id}/schedule` sends the loaded `version` and gives 200 with the status `Scheduled`. The page shows `Scheduled`, `Cancel workshop`, and `Mark completed`. `Schedule` and `Edit` are gone. Click `Cancel workshop`. The dialog `Cancel this workshop?` shows. Click `Keep workshop`. The dialog closes, no `POST .../cancel` goes out, and `Cancel workshop` has the focus. -- **Search.** Open `/workshops`, type a word of the title into the searchbox `Search workshops`. The URL gets `?search=<word>`, and `GET /api/v1/workshops` has the same `search`. The row of the workshop shows, with the start in the zone of the venue. +- **Search.** Open `/workshops`, type a word of the title into the searchbox `Search workshops`. The URL gets `?search=<word>`, and `GET /api/v1/workshops` has `filters=title @=* "<word>"`. Text with a `"` goes in a padded raw string, as `docs/backend/features-and-cqrs.md`, "Search text", says. The row of the workshop shows, with the start in the zone of the venue. - **Proof.** Run `node $S/scripts/browse.mjs $S/recipes/examples/workshops.mjs`. The captures `no-tenant-list`, `empty-list`, `venue-picked`, `detail-draft`, `stale-alert`, `latest-loaded`, `scheduled`, `cancel-dialog`, and `search` show the states. ## Gotchas diff --git a/.agents/skills/verify-fullstack-template/recipes/examples/workshops.mjs b/.agents/skills/verify-fullstack-template/recipes/examples/workshops.mjs index 354866742..9534752ef 100644 --- a/.agents/skills/verify-fullstack-template/recipes/examples/workshops.mjs +++ b/.agents/skills/verify-fullstack-template/recipes/examples/workshops.mjs @@ -191,11 +191,11 @@ export default async ({ page, context, step, capture, settle, expect, login }) = expect(sent).toBe(0) }) - await step('search: the URL and the request have the search, and the row shows', async () => { + await step('search: the URL has the search, the request has its title filter, and the row shows', async () => { await page.goto('/workshops') await settle() const searched = page.waitForResponse( - (r) => new URL(r.url()).pathname === '/api/v1/workshops' && new URL(r.url()).searchParams.get('search') === stamp, + (r) => new URL(r.url()).pathname === '/api/v1/workshops' && new URL(r.url()).searchParams.get('filters') === `title @=* "${stamp}"`, ) await page.getByRole('searchbox', { name: 'Search workshops' }).fill(stamp) expect((await searched).status()).toBe(200) diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md index 71c431c3e..53201d7a4 100644 --- a/.agents/skills/writing-tests/SKILL.md +++ b/.agents/skills/writing-tests/SKILL.md @@ -70,7 +70,7 @@ Examples: | A new query hook or an error toast | `pnpm test` and `pnpm test:e2e` | | A new auth provider, or a change to the cookie or the refresh of the BFF | `pnpm test:e2e:stack` against that provider | | A change to the `/api` proxy of the Vite dev server | Both Playwright suites | -| A new search on a list | An integration test with `%`, `_`, and `\` in the search. See `docs/backend.md`, section "Tests" | +| A new text field that a list filters with `@=*` | An integration test with `%`, `_`, `\`, and a quote at an end in the filter value, built with `QueryKitText.Quote`. See `docs/backend.md`, section "Tests" | ## Write a functional test diff --git a/FullstackTemplate.Server/Examples/Venues/Dtos/VenueParametersDto.cs b/FullstackTemplate.Server/Examples/Venues/Dtos/VenueParametersDto.cs index 20e7f6d23..2209066bc 100644 --- a/FullstackTemplate.Server/Examples/Venues/Dtos/VenueParametersDto.cs +++ b/FullstackTemplate.Server/Examples/Venues/Dtos/VenueParametersDto.cs @@ -4,22 +4,17 @@ namespace FullstackTemplate.Server.Examples.Venues.Dtos; public sealed class VenueParametersDto : BasePaginationParameters { - public const int SearchMaxLength = Venue.NameMaxLength; - public string? Filters { get; set; } public string? SortOrder { get; set; } - public string? Search { get; set; } - public static VenueParametersDto From( - int? pageNumber, int? pageSize, string? filters, string? sortOrder, string? search) + int? pageNumber, int? pageSize, string? filters, string? sortOrder) { var parameters = new VenueParametersDto { Filters = string.IsNullOrEmpty(filters) ? null : filters, SortOrder = string.IsNullOrEmpty(sortOrder) ? null : sortOrder, - Search = string.IsNullOrWhiteSpace(search) ? null : search.Trim(), }; parameters.SetPage(pageNumber, pageSize); return parameters; diff --git a/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.Http.cs b/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.Http.cs index 8e8c194b7..316862f82 100644 --- a/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.Http.cs +++ b/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.Http.cs @@ -18,18 +18,17 @@ public void Map(IEndpointRouteBuilder versionedGroup) => versionedGroup .ProducesValidationProblem(); /// <summary> - /// Gets a paginated list of Venues. The search finds the venues whose name contains the text. + /// Gets a paginated list of Venues. /// </summary> public static async Task<Ok<PagedList<VenueDto>>> Handle( [MaxLength(CustomQueryKitConfiguration.FilterMaxLength)] string? filters, string? sortOrder, - [MaxLength(VenueParametersDto.SearchMaxLength)] string? search, [Range(1, BasePaginationParameters.MaxPageNumber)] int? pageNumber, [Range(1, int.MaxValue)] int? pageSize, IMediator mediator, CancellationToken cancellationToken) { - var parameters = VenueParametersDto.From(pageNumber, pageSize, filters, sortOrder, search); + var parameters = VenueParametersDto.From(pageNumber, pageSize, filters, sortOrder); var result = await mediator.Send(new GetVenueList.Query(parameters), cancellationToken); return TypedResults.Ok(result); diff --git a/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.cs b/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.cs index 89bc51978..1eee742d7 100644 --- a/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.cs +++ b/FullstackTemplate.Server/Examples/Venues/Features/GetVenueList/GetVenueList.cs @@ -2,7 +2,6 @@ namespace FullstackTemplate.Server.Examples.Venues.Features; using Databases; using Dtos; -using Exceptions; using Mappings; using MediatR; using Microsoft.EntityFrameworkCore; @@ -14,29 +13,14 @@ public sealed record Query(VenueParametersDto Parameters) : IRequest<PagedList<V public sealed class Handler(AppDbContext dbContext) : IRequestHandler<Query, PagedList<VenueDto>> { - private const string SearchParameter = "search"; - public async Task<PagedList<VenueDto>> Handle(Query request, CancellationToken cancellationToken) { var queryKitConfig = new CustomQueryKitConfiguration(); - var venues = dbContext.Venues + var query = dbContext.Venues .TagWithOperationCallSite("venues.list") - .AsNoTracking(); - - if (request.Parameters.Search is { } search) - { - if (search.Length > VenueParametersDto.SearchMaxLength) - throw new QueryInputException(SearchParameter, - $"A search can have no more than {VenueParametersDto.SearchMaxLength} characters."); - if (!PostgresText.CanStore(search)) - throw new QueryInputException(SearchParameter, "The search has a character that is not allowed."); - - var pattern = LikePattern.Containing(search); - venues = venues.Where(v => EF.Functions.ILike(v.Name, pattern, LikePattern.EscapeCharacter)); - } - - var query = venues.ToVenueDtoQueryable(); + .AsNoTracking() + .ToVenueDtoQueryable(); if (!string.IsNullOrWhiteSpace(request.Parameters.Filters)) query = query.ApplyFilters(request.Parameters.Filters, queryKitConfig); diff --git a/FullstackTemplate.Server/Examples/Workshops/Dtos/WorkshopParametersDto.cs b/FullstackTemplate.Server/Examples/Workshops/Dtos/WorkshopParametersDto.cs index 88e7bb5cb..2cf10d087 100644 --- a/FullstackTemplate.Server/Examples/Workshops/Dtos/WorkshopParametersDto.cs +++ b/FullstackTemplate.Server/Examples/Workshops/Dtos/WorkshopParametersDto.cs @@ -4,22 +4,17 @@ namespace FullstackTemplate.Server.Examples.Workshops.Dtos; public sealed class WorkshopParametersDto : BasePaginationParameters { - public const int SearchMaxLength = Workshop.TitleMaxLength; - public string? Filters { get; set; } public string? SortOrder { get; set; } - public string? Search { get; set; } - public static WorkshopParametersDto From( - int? pageNumber, int? pageSize, string? filters, string? sortOrder, string? search) + int? pageNumber, int? pageSize, string? filters, string? sortOrder) { var parameters = new WorkshopParametersDto { Filters = string.IsNullOrEmpty(filters) ? null : filters, SortOrder = string.IsNullOrEmpty(sortOrder) ? null : sortOrder, - Search = string.IsNullOrWhiteSpace(search) ? null : search.Trim(), }; parameters.SetPage(pageNumber, pageSize); return parameters; diff --git a/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Http.cs b/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Http.cs index de3e4e4f9..41df5b414 100644 --- a/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Http.cs +++ b/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Http.cs @@ -18,18 +18,17 @@ public void Map(IEndpointRouteBuilder versionedGroup) => versionedGroup .ProducesValidationProblem(); /// <summary> - /// Gets a paginated list of Workshops. The search finds the workshops whose title contains the text. + /// Gets a paginated list of Workshops. /// </summary> public static async Task<Ok<PagedList<WorkshopDto>>> Handle( [MaxLength(CustomQueryKitConfiguration.FilterMaxLength)] string? filters, string? sortOrder, - [MaxLength(WorkshopParametersDto.SearchMaxLength)] string? search, [Range(1, BasePaginationParameters.MaxPageNumber)] int? pageNumber, [Range(1, int.MaxValue)] int? pageSize, IMediator mediator, CancellationToken cancellationToken) { - var parameters = WorkshopParametersDto.From(pageNumber, pageSize, filters, sortOrder, search); + var parameters = WorkshopParametersDto.From(pageNumber, pageSize, filters, sortOrder); var result = await mediator.Send(new GetWorkshopList.Query(parameters), cancellationToken); return TypedResults.Ok(result); diff --git a/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Mcp.cs b/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Mcp.cs index 35fa14cca..9570db4a4 100644 --- a/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Mcp.cs +++ b/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.Mcp.cs @@ -19,13 +19,12 @@ public static class GetWorkshopListTool public static async Task<McpPage<WorkshopDto>> Handle( IMediator mediator, CancellationToken cancellationToken, - [Description("A text that the title contains, with no regard to case.")] string? search = null, [Description("The page number. The first page is 1. Leave it out for the first page.")] int? pageNumber = null, [Description("The number of workshops on a page, at least 1. Leave it out for the default size. A value more than the maximum gives the maximum. The result gives the size that was used.")] int? pageSize = null, - [Description("A QueryKit filter on the fields of a workshop, for example: status == \"Scheduled\"")] string? filters = null, + [Description("A QueryKit filter on the fields of a workshop, for example: title @=* \"text\". Put text with a \" in a raw string with one space on each side, for example: title @=* \"\"\" say \"hi\" \"\"\". Its delimiter is one quote more than the longest run of quotes in the text, and at least three quotes.")] string? filters = null, [Description("A QueryKit sort order, for example: -startsAt")] string? sortOrder = null) { - var parameters = WorkshopParametersDto.From(pageNumber, pageSize, filters, sortOrder, search); + var parameters = WorkshopParametersDto.From(pageNumber, pageSize, filters, sortOrder); var result = await mediator.Send(new GetWorkshopList.Query(parameters), cancellationToken); return McpPage.From(result); } diff --git a/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.cs b/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.cs index 091181b77..1fa67e8c1 100644 --- a/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.cs +++ b/FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.cs @@ -3,7 +3,6 @@ namespace FullstackTemplate.Server.Examples.Workshops.Features; using Databases; using Domain.Users; using Dtos; -using Exceptions; using Mappings; using MediatR; using Microsoft.EntityFrameworkCore; @@ -16,31 +15,16 @@ public sealed record Query(WorkshopParametersDto Parameters) : IRequest<PagedLis public sealed class Handler(AppDbContext dbContext, IPermissionGuard permissionGuard) : IRequestHandler<Query, PagedList<WorkshopDto>> { - private const string SearchParameter = "search"; - public async Task<PagedList<WorkshopDto>> Handle(Query request, CancellationToken cancellationToken) { var caller = await permissionGuard.GetCallerAsync(cancellationToken); var queryKitConfig = new CustomQueryKitConfiguration(); - var workshops = dbContext.Workshops + var query = dbContext.Workshops .TagWithOperationCallSite("workshops.list") - .AsNoTracking(); - - if (request.Parameters.Search is { } search) - { - if (search.Length > WorkshopParametersDto.SearchMaxLength) - throw new QueryInputException(SearchParameter, - $"A search can have no more than {WorkshopParametersDto.SearchMaxLength} characters."); - if (!PostgresText.CanStore(search)) - throw new QueryInputException(SearchParameter, "The search has a character that is not allowed."); - - var pattern = LikePattern.Containing(search); - workshops = workshops.Where(w => EF.Functions.ILike(w.Title, pattern, LikePattern.EscapeCharacter)); - } - - var query = workshops.ToWorkshopDtoQueryable(dbContext.Venues); + .AsNoTracking() + .ToWorkshopDtoQueryable(dbContext.Venues); if (!string.IsNullOrWhiteSpace(request.Parameters.Filters)) query = query.ApplyFilters(request.Parameters.Filters, queryKitConfig); diff --git a/FullstackTemplate.Server/openapi/FullstackTemplate.Server.json b/FullstackTemplate.Server/openapi/FullstackTemplate.Server.json index 607fd63eb..a6a4f7a1b 100644 --- a/FullstackTemplate.Server/openapi/FullstackTemplate.Server.json +++ b/FullstackTemplate.Server/openapi/FullstackTemplate.Server.json @@ -1759,7 +1759,7 @@ "tags": [ "Venues" ], - "summary": "Gets a paginated list of Venues. The search finds the venues whose name contains the text.", + "summary": "Gets a paginated list of Venues.", "operationId": "GetVenueList", "parameters": [ { @@ -1777,14 +1777,6 @@ "type": "string" } }, - { - "name": "search", - "in": "query", - "schema": { - "maxLength": 200, - "type": "string" - } - }, { "name": "pageNumber", "in": "query", @@ -2011,7 +2003,7 @@ "tags": [ "Workshops" ], - "summary": "Gets a paginated list of Workshops. The search finds the workshops whose title contains the text.", + "summary": "Gets a paginated list of Workshops.", "operationId": "GetWorkshopList", "parameters": [ { @@ -2029,14 +2021,6 @@ "type": "string" } }, - { - "name": "search", - "in": "query", - "schema": { - "maxLength": 200, - "type": "string" - } - }, { "name": "pageNumber", "in": "query", diff --git a/docs/backend.md b/docs/backend.md index 9c9b5a4ae..5f666cb5e 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -255,7 +255,7 @@ A test never takes today from the UTC date. Take it from the zone of the place i TUnit runs all tests in parallel, also the tests of one class. The integration and functional tests share one fixture for each assembly, which `AssemblyHooks.cs` starts and stops. Each test must create its own data and must not depend on rows from other tests. If a test reads state of the whole process, such as all exported spans, put `[NotInParallel]` on its class. -A list with a search has an integration test that searches for `50%`, `a_b`, and `c\d`, and finds only the row with that text. See `tests/FullstackTemplate.IntegrationTests/Databases/LikePatternTests.cs`. +A list has an integration test that filters its text field with `@=*` for `50%`, `a_b`, `c\d`, and text with a quote at an end, and finds only the row with that text. Build each filter value with `QueryKitText.Quote`. A raw `ILike` with `LikePattern` has the same test. See `tests/FullstackTemplate.IntegrationTests/Databases/LikePatternTests.cs`. To run the tests in a web UI, open the **Labcoat UI** link of the `tests` resource in the Aspire dashboard. [Labcoat](https://github.com/eriklieben/labcoat) builds and runs the test projects, and shows each failure with its source. diff --git a/docs/backend/features-and-cqrs.md b/docs/backend/features-and-cqrs.md index 780587c39..06155c879 100644 --- a/docs/backend/features-and-cqrs.md +++ b/docs/backend/features-and-cqrs.md @@ -281,17 +281,17 @@ public static class GetUserList ### Search text -A free-text search of a list uses `EF.Functions.ILike(column, LikePattern.Containing(search), LikePattern.EscapeCharacter)`. A name check that ignores case uses `LikePattern.Exactly`, and a prefix match uses `LikePattern.StartingWith`. `LikePattern` escapes `%`, `_`, and `\`, so a search for `50%` or `a_b` finds only the rows with that text. A name check gives a clear error, but only a unique index on the name stops two requests that save the same name at one time. +A list has no `search` parameter. A caller finds text through `filters`, with the QueryKit operator `@=*` (contains, ignore case), for example `title @=* "text"`. EF Core escapes the pattern of the QueryKit contains, starts-with, and ends-with operators, so a filter for `50%` or `a_b` finds only the rows with that text. `ApplyFilters` refuses a filter that fails `PostgresText.CanStore`, with the `filters` parameter. See [Validation](#validation). -`BannedSymbols.txt` bans the two-argument `ILike` and `Like` (RS0030). They send `ESCAPE ''`, so the backslash of an escaped pattern escapes nothing. - -Trim the search, and give it a max length on the parameters DTO. If the search is empty after the trim, do not apply it. If the search fails `PostgresText.CanStore`, throw a `QueryInputException` with the name of the parameter. See [Validation](#validation). Apply the search before `ApplyFilters`, on the entity or on the DTO projection. The query keeps its fixed sort. +QueryKit has no escape in a quoted value. Text with a `"` goes in a raw string with one space of padding on each side, for example `title @=* """ say "hi" """`. The delimiter is one quote longer than the longest run of quotes in the text, and at least three quotes long. QueryKit removes the padding, so a quote at the start or the end of the text stays in the text. Give the MCP description of `filters` this rule, as the lists that `scripts/new-feature.cs` writes do. `QueryKitText.Quote` in the shared test helpers and `quoteText` in `frontend/src/lib/querykit-text.ts` write it. <!-- example:start --> -The workshop list searches the title: [`GetWorkshopList.Handler.Handle`](../../FullstackTemplate.Server/Examples/Workshops/Features/GetWorkshopList/GetWorkshopList.cs). +The workshop list test finds titles with `%`, `_`, `\`, and quotes through a filter: [`WorkshopListQueryTests`](../../tests/FullstackTemplate.IntegrationTests/Examples/Workshops/WorkshopListQueryTests.cs). <!-- example:end --> -A QueryKit filter needs no `LikePattern`. EF Core escapes the pattern of its contains, starts-with, and ends-with operators. +A raw `EF.Functions.ILike` outside QueryKit, such as a name check that ignores case or a prefix match, uses `LikePattern`: `LikePattern.Exactly` for a name check, `LikePattern.StartingWith` for a prefix, and `LikePattern.Containing` for a contains, each with `LikePattern.EscapeCharacter` as the third argument. `LikePattern` escapes `%`, `_`, and `\`. A name check gives a clear error, but only a unique index on the name stops two requests that save the same name at one time. + +`BannedSymbols.txt` bans the two-argument `ILike` and `Like` (RS0030). They send `ESCAPE ''`, so the backslash of an escaped pattern escapes nothing. ## Permission checks diff --git a/docs/frontend.md b/docs/frontend.md index e335fdeac..a1e3c3601 100644 --- a/docs/frontend.md +++ b/docs/frontend.md @@ -191,6 +191,8 @@ The router moves the `component` of each route to a chunk that loads when the pa }) ``` + A param that the contract does not have, such as the search text of a list that the hook turns into a filter, gets its own schema with the max length of the field that it matches: `z.string().max(searchMaxLength).optional().catch(undefined)`. + zod has its own vendor chunk (`vendorChunks` in `frontend/vite.config.ts`), so it is not in the entry chunk. When a route checks its search with zod, the zod chunk loads on each first page. It is 67 kB, 18 kB with gzip. - Import a type with a top-level `import type`. Do not write `import { Thing, type Option }`. The router keeps the import of a type that the component uses as `import { type Option }`, and TypeScript keeps that line as an import of the module. So the module and each module that it imports load with the entry chunk. `pnpm lint` fails on an inline type import in `routes/`. - Do not import a component or a large library in `validateSearch`, `loader`, or `beforeLoad`. @@ -299,5 +301,5 @@ const schema = z.object({ firstName: stringWithMaxLengthOf(firstName).min(1, 'Re ``` <!-- example:start --> -The workshop forms read the max length of the title and the maximum of the capacity from the contract: [`limitsOf`](<../frontend/src/examples/workshops/components/workshop-fields-schema.ts>) and [`workshopFieldsSchema`](<../frontend/src/examples/workshops/components/workshop-fields-schema.ts>). The search boxes read the max length of the `search` query parameter: [`searchMaxLength`](<../frontend/src/routes/(examples)/workshops/index.tsx>) and [`searchMaxLength`](<../frontend/src/examples/venues/components/venue-picker.tsx>). The venue picker keeps a pick that no loaded page has, by loading it by its ID: [`optionsWithPick`](<../frontend/src/examples/venues/components/venue-picker.tsx>). +The workshop forms read the max length of the title and the maximum of the capacity from the contract: [`limitsOf`](<../frontend/src/examples/workshops/components/workshop-fields-schema.ts>) and [`workshopFieldsSchema`](<../frontend/src/examples/workshops/components/workshop-fields-schema.ts>). The search boxes read the max length of the field that their filter matches, the title and the venue name: [`searchMaxLength`](<../frontend/src/routes/(examples)/workshops/index.tsx>) and [`searchMaxLength`](<../frontend/src/examples/venues/components/venue-picker.tsx>). The list hooks turn the text into a filter with [`containsText`](../frontend/src/lib/querykit-text.ts). The venue picker keeps a pick that no loaded page has, by loading it by its ID: [`optionsWithPick`](<../frontend/src/examples/venues/components/venue-picker.tsx>). <!-- example:end --> diff --git a/docs/frontend/client-state.md b/docs/frontend/client-state.md index f78c49879..c291fceaf 100644 --- a/docs/frontend/client-state.md +++ b/docs/frontend/client-state.md @@ -16,7 +16,7 @@ Use the first item in this list that fits: The app has no global store library. Before you add one, make sure that items 1 to 6 do not fit. <!-- example:start --> -The workshop list keeps its search and its page in the search params. The contract schemas validate them, and a value that the contract refuses falls back to the default: [`listSearchSchema`](<../../frontend/src/routes/(examples)/workshops/index.tsx>). A search that arrives after a link or Back changed the URL does not overwrite the URL: [`handleSearch`](<../../frontend/src/routes/(examples)/workshops/index.tsx>). +The workshop list keeps its search and its page in the search params. A zod schema validates them, and a value that it refuses falls back to the default. The page comes from the contract schema. The search is plain text, because the list hook turns it into a filter: [`listSearchSchema`](<../../frontend/src/routes/(examples)/workshops/index.tsx>). A search that arrives after a link or Back changed the URL does not overwrite the URL: [`handleSearch`](<../../frontend/src/routes/(examples)/workshops/index.tsx>). <!-- example:end --> ## Calculate, do not store diff --git a/docs/frontend/server-state.md b/docs/frontend/server-state.md index dde731122..f14c0b127 100644 --- a/docs/frontend/server-state.md +++ b/docs/frontend/server-state.md @@ -64,7 +64,7 @@ Give the `signal` to the client, so that TanStack Query can cancel the request. When more than one place uses the same query, put the key, the function, and the options in one `queryOptions` object. Then `useQuery`, `useSuspenseQuery`, and `queryClient.prefetchQuery` can share it. <!-- example:start --> -The workshop example has one `queryOptions` for the detail: [`workshopQueryOptions`](<../../frontend/src/examples/workshops/apis/get-workshop.ts>). The list keeps the last page on the screen while the next one loads: [`useWorkshopList`](<../../frontend/src/examples/workshops/apis/get-workshop-list.ts>). The venue picker loads its search one page at a time with `useInfiniteQuery`: [`useVenueSearch`](<../../frontend/src/examples/venues/apis/get-venue-list.ts>). +The workshop example has one `queryOptions` for the detail: [`workshopQueryOptions`](<../../frontend/src/examples/workshops/apis/get-workshop.ts>). The list keeps the last page on the screen while the next one loads, and it turns the search into a `filters` value with `containsText`: [`useWorkshopList`](<../../frontend/src/examples/workshops/apis/get-workshop-list.ts>). The venue picker loads its search one page at a time with `useInfiniteQuery`: [`useVenueSearch`](<../../frontend/src/examples/venues/apis/get-venue-list.ts>). <!-- example:end --> ## Mutation diff --git a/docs/frontend/testing.md b/docs/frontend/testing.md index 16dd8c1e3..849e1f49d 100644 --- a/docs/frontend/testing.md +++ b/docs/frontend/testing.md @@ -31,7 +31,7 @@ A click on an option of a combobox can scroll the page, and a scroll of the page When a component test fails in CI, open the `.vitest/attachments/` folder in the test report artifact of the job. It has the failure screenshot and the Playwright trace of each failed test. The screenshot is at `failure-screenshots/<path of the test file>/<full test name>.png`, with a `-` in place of each character that is not a letter, a digit, or `_`. Vitest 5.0.5 puts only the file name of the test file in that path. So when two files of one name in two folders had a failed test of the same name, one screenshot replaced the other. The patch of `@vitest/browser` in `frontend/patches/` puts the path of the file there. Open the trace at https://trace.playwright.dev. For a test that timed out, the last action with no end is the step that the test waited on. Only CI records the traces, because they make `pnpm test` about 50% slower. In CI that is 16 s more for each job: the median of 8 runs with traces and 8 runs without traces, on one commit, in each of the `api-contract` and `without-examples` jobs. To record them locally, run `CI=1 pnpm test`. <!-- example:start --> -The workshop example has these component tests: the limits of the contract and the stale-version reload of the edit form ([`refuses a title and a capacity over the limits of the contract`](<../../frontend/src/examples/workshops/components/workshop-edit-form.test.tsx>), [`after a stale save, loads the latest`](<../../frontend/src/examples/workshops/components/workshop-edit-form.test.tsx>)), the venue picker with a pick that is not on the first page ([`shows a picked venue that is not on the first page`](<../../frontend/src/examples/venues/components/venue-picker.test.tsx>)), and the search and the page of the list in the URL ([`puts the page in the URL`](<../../frontend/src/examples/workshops/workshop-list.test.tsx>)). +The workshop example has these component tests: the limits of the contract and the stale-version reload of the edit form ([`refuses a title and a capacity over the limits of the contract`](<../../frontend/src/examples/workshops/components/workshop-edit-form.test.tsx>), [`after a stale save, loads the latest`](<../../frontend/src/examples/workshops/components/workshop-edit-form.test.tsx>)), the venue picker with a pick that is not on the first page ([`shows a picked venue that is not on the first page`](<../../frontend/src/examples/venues/components/venue-picker.test.tsx>)), and the search and the page of the list in the URL ([`puts the page in the URL`](<../../frontend/src/examples/workshops/workshop-list.test.tsx>)). A unit test checks the filter that a search sends, with a quote at an end, `%`, and `_` ([`containsText`](../../frontend/src/lib/querykit-text.test.ts)). <!-- example:end --> ## The functional suite diff --git a/frontend/src/api/generated/venues/clients/get-venue-list.ts b/frontend/src/api/generated/venues/clients/get-venue-list.ts index 73c29e0cd..fa423d416 100644 --- a/frontend/src/api/generated/venues/clients/get-venue-list.ts +++ b/frontend/src/api/generated/venues/clients/get-venue-list.ts @@ -8,7 +8,7 @@ import type { GetVenueListOptions, GetVenueListResponses } from '../types/get-ve import { client, withUnwrap } from '../../.kubb/client' /** - * @summary Gets a paginated list of Venues. The search finds the venues whose name contains the text. + * @summary Gets a paginated list of Venues. * {@link /api/v1/venues} */ export function getVenueList<ThrowOnError extends boolean = true>(options: Options<GetVenueListOptions, ThrowOnError> = {}): Unwrappable<RequestResult<GetVenueListResponses, ThrowOnError>> { diff --git a/frontend/src/api/generated/venues/types/get-venue-list.ts b/frontend/src/api/generated/venues/types/get-venue-list.ts index 43a389c12..fece5bb2b 100644 --- a/frontend/src/api/generated/venues/types/get-venue-list.ts +++ b/frontend/src/api/generated/venues/types/get-venue-list.ts @@ -13,11 +13,6 @@ export type GetVenueListQuery = { */ filters?: string; sortOrder?: string; - /** - * @maxLength 200 - * @type string | undefined - */ - search?: string; /** * @description * Format: `int32` diff --git a/frontend/src/api/generated/venues/zod/get-venue-list.ts b/frontend/src/api/generated/venues/zod/get-venue-list.ts index 8dda271df..6f9cf6c88 100644 --- a/frontend/src/api/generated/venues/zod/get-venue-list.ts +++ b/frontend/src/api/generated/venues/zod/get-venue-list.ts @@ -11,8 +11,6 @@ export const getVenueListQueryFiltersSchema = z.string().max(2000).optional() export const getVenueListQuerySortOrderSchema = z.string().optional() -export const getVenueListQuerySearchSchema = z.string().max(200).optional() - export const getVenueListQueryPageNumberSchema = z.int32().min(1).max(4294967).optional() export const getVenueListQueryPageSizeSchema = z.int32().min(1).max(2147483647).optional() diff --git a/frontend/src/api/generated/workshops/clients/get-workshop-list.ts b/frontend/src/api/generated/workshops/clients/get-workshop-list.ts index e1f8d245b..3eac1d46b 100644 --- a/frontend/src/api/generated/workshops/clients/get-workshop-list.ts +++ b/frontend/src/api/generated/workshops/clients/get-workshop-list.ts @@ -8,7 +8,7 @@ import type { GetWorkshopListOptions, GetWorkshopListResponses } from '../types/ import { client, withUnwrap } from '../../.kubb/client' /** - * @summary Gets a paginated list of Workshops. The search finds the workshops whose title contains the text. + * @summary Gets a paginated list of Workshops. * {@link /api/v1/workshops} */ export function getWorkshopList<ThrowOnError extends boolean = true>(options: Options<GetWorkshopListOptions, ThrowOnError> = {}): Unwrappable<RequestResult<GetWorkshopListResponses, ThrowOnError>> { diff --git a/frontend/src/api/generated/workshops/types/get-workshop-list.ts b/frontend/src/api/generated/workshops/types/get-workshop-list.ts index 5decc8a18..4f0313b1e 100644 --- a/frontend/src/api/generated/workshops/types/get-workshop-list.ts +++ b/frontend/src/api/generated/workshops/types/get-workshop-list.ts @@ -13,11 +13,6 @@ export type GetWorkshopListQuery = { */ filters?: string; sortOrder?: string; - /** - * @maxLength 200 - * @type string | undefined - */ - search?: string; /** * @description * Format: `int32` diff --git a/frontend/src/api/generated/workshops/zod/get-workshop-list.ts b/frontend/src/api/generated/workshops/zod/get-workshop-list.ts index 90a60968c..28e3ea965 100644 --- a/frontend/src/api/generated/workshops/zod/get-workshop-list.ts +++ b/frontend/src/api/generated/workshops/zod/get-workshop-list.ts @@ -11,8 +11,6 @@ export const getWorkshopListQueryFiltersSchema = z.string().max(2000).optional() export const getWorkshopListQuerySortOrderSchema = z.string().optional() -export const getWorkshopListQuerySearchSchema = z.string().max(200).optional() - export const getWorkshopListQueryPageNumberSchema = z.int32().min(1).max(4294967).optional() export const getWorkshopListQueryPageSizeSchema = z.int32().min(1).max(2147483647).optional() diff --git a/frontend/src/components/filter-builder/utils/querykit-converter.ts b/frontend/src/components/filter-builder/utils/querykit-converter.ts index c7299c300..6744764f4 100644 --- a/frontend/src/components/filter-builder/utils/querykit-converter.ts +++ b/frontend/src/components/filter-builder/utils/querykit-converter.ts @@ -1,5 +1,6 @@ import { toCalendarDate } from '@internationalized/date' +import { quoteText } from '@/lib/querykit-text' import { offsetAt, wallClockAt } from '@/lib/zoned-time' import type { Filter, FilterGroup, FilterState, DateValue } from '../types' @@ -61,21 +62,6 @@ function convertTextFilter(propertyKey: string, operator: string, value: string) return `${propertyKey} ${operator} ${quoteText(value)}` } -/** - * QueryKit reads an unquoted value as a name, a number, or `null`, and it has no escape in `"..."`. So a value with a - * quote goes in a raw literal: the value between runs of quotes that are longer than each run in the value, and at - * least three long. One space pads each side, and QueryKit removes it, so a quote at the start or the end of the value - * stays part of the value. - */ -function quoteText(value: string): string { - if (!value.includes('"')) { - return `"${value}"` - } - const longestRun = Math.max(...(value.match(/"+/g) ?? []).map((run) => run.length)) - const delimiter = '"'.repeat(Math.max(3, longestRun + 1)) - return `${delimiter} ${value} ${delimiter}` -} - /** * Convert a multiselect filter to QueryKit string */ diff --git a/frontend/src/components/search-box.tsx b/frontend/src/components/search-box.tsx index ba0cd8e2a..c3df0f065 100644 --- a/frontend/src/components/search-box.tsx +++ b/frontend/src/components/search-box.tsx @@ -9,7 +9,7 @@ interface SearchBoxProps { placeholder?: string /** The search in the URL. */ search: string - /** The limit of the search parameter in the contract, from `maxLengthOf`. */ + /** The max length of the field that the search matches, from `maxLengthOf`. */ maxLength: number /** After the debounce. `base` is the search of the URL when the user typed, so the page can drop a search that a later navigation replaced. */ onSearch: (text: string, base: string) => void diff --git a/frontend/src/examples/venues/apis/get-venue-list.ts b/frontend/src/examples/venues/apis/get-venue-list.ts index 681a29356..69a6eab64 100644 --- a/frontend/src/examples/venues/apis/get-venue-list.ts +++ b/frontend/src/examples/venues/apis/get-venue-list.ts @@ -1,7 +1,9 @@ import { keepPreviousData, useInfiniteQuery } from '@tanstack/react-query' +import type { VenueDto } from '@/api/generated/models/types/venue-dto' import { getVenueList } from '@/api/generated/venues/clients/get-venue-list' import { parsePagination } from '@/lib/pagination' +import { containsText } from '@/lib/querykit-text' import { VenueKeys } from './venue.keys' @@ -12,7 +14,7 @@ export function useVenueSearch(search: string) { queryKey: VenueKeys.list(search), queryFn: async ({ pageParam, signal }) => { const result = await getVenueList({ - query: { search: search || undefined, pageNumber: pageParam, pageSize: VENUE_PAGE_SIZE }, + query: { filters: containsText<VenueDto>('name', search), pageNumber: pageParam, pageSize: VENUE_PAGE_SIZE }, signal, }) return { venues: result.data, pagination: parsePagination(result) } diff --git a/frontend/src/examples/venues/components/venue-picker.test.tsx b/frontend/src/examples/venues/components/venue-picker.test.tsx index a654f565e..ee98b5a4f 100644 --- a/frontend/src/examples/venues/components/venue-picker.test.tsx +++ b/frontend/src/examples/venues/components/venue-picker.test.tsx @@ -6,7 +6,7 @@ import { render } from 'vitest-browser-react' import type { VenueDto } from '@/api/generated/models/types/venue-dto' import type { Answer } from '@/test/answer' -import { getVenueListQuerySearchSchema } from '@/api/generated/venues/zod/get-venue-list' +import { venueForCreationDtoSchema } from '@/api/generated/models/zod/venue-for-creation-dto' import { maxLengthOf } from '@/lib/api-contract' import { VenueKeys } from '../apis/venue.keys' @@ -43,7 +43,7 @@ async function renderPicker(initial = '', ...more: Answer[]) { { method: 'GET', path: `/api/v1/venues/${firstPage[0].id}`, body: firstPage[0] }, { method: 'GET', path: '/api/v1/venues', query: { pageNumber: '2' }, headers: pagination(2, 2), body: [venue(11)] }, { method: 'GET', path: `/api/v1/venues/${offPage.id}`, body: offPage }, - { method: 'GET', path: '/api/v1/venues', query: { search: 'Zeta' }, headers: pagination(1, 1), body: [offPage] }, + { method: 'GET', path: '/api/v1/venues', query: { filters: 'name @=* "Zeta"' }, headers: pagination(1, 1), body: [offPage] }, ...more, ]) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) @@ -84,10 +84,10 @@ test('finds a venue by a search on the Server, and keeps the pick when the searc await expect.element(screen.getByRole('option', { name: 'Venue 1', exact: true })).toBeVisible() }) -test('takes no more search text than the contract allows', async () => { +test('takes no more search text than a venue name can hold', async () => { const { input } = await renderPicker() - await expect.element(input).toHaveAttribute('maxlength', String(maxLengthOf(getVenueListQuerySearchSchema.unwrap()))) + await expect.element(input).toHaveAttribute('maxlength', String(maxLengthOf(venueForCreationDtoSchema.shape.name))) }) test('says that the venues did not load when the search fails, and searches again when the list opens again', async () => { diff --git a/frontend/src/examples/venues/components/venue-picker.tsx b/frontend/src/examples/venues/components/venue-picker.tsx index 739cecf40..71f534d66 100644 --- a/frontend/src/examples/venues/components/venue-picker.tsx +++ b/frontend/src/examples/venues/components/venue-picker.tsx @@ -3,7 +3,7 @@ import { useQueryClient } from '@tanstack/react-query' import { Collection, Text, type Key } from 'react-aria-components' import type { VenueDto } from '@/api/generated/models/types/venue-dto' -import { getVenueListQuerySearchSchema } from '@/api/generated/venues/zod/get-venue-list' +import { venueForCreationDtoSchema } from '@/api/generated/models/zod/venue-for-creation-dto' import { Combobox, ComboboxContent, @@ -21,7 +21,7 @@ import { useVenue } from '../apis/get-venue' import { useVenueSearch } from '../apis/get-venue-list' import { VenueKeys } from '../apis/venue.keys' -const searchMaxLength = maxLengthOf(getVenueListQuerySearchSchema.unwrap()) +const searchMaxLength = maxLengthOf(venueForCreationDtoSchema.shape.name) /** * The options are the pages of the search, with the picked venue from its detail query. React Aria shows the name of diff --git a/frontend/src/examples/workshops/apis/get-workshop-list.ts b/frontend/src/examples/workshops/apis/get-workshop-list.ts index 66226e558..09adbfcef 100644 --- a/frontend/src/examples/workshops/apis/get-workshop-list.ts +++ b/frontend/src/examples/workshops/apis/get-workshop-list.ts @@ -1,7 +1,9 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query' +import type { WorkshopDto } from '@/api/generated/models/types/workshop-dto' import { getWorkshopList } from '@/api/generated/workshops/clients/get-workshop-list' import { parsePagination } from '@/lib/pagination' +import { containsText } from '@/lib/querykit-text' import { WorkshopKeys } from './workshop.keys' @@ -18,7 +20,11 @@ export function useWorkshopList(params: WorkshopListParams, { enabled = true }: queryKey: WorkshopKeys.list(params), queryFn: async ({ signal }) => { const result = await getWorkshopList({ - query: { search: params.search || undefined, pageNumber: params.page, pageSize: WORKSHOP_PAGE_SIZE }, + query: { + filters: containsText<WorkshopDto>('title', params.search), + pageNumber: params.page, + pageSize: WORKSHOP_PAGE_SIZE, + }, signal, }) return { workshops: result.data, pagination: parsePagination(result) } diff --git a/frontend/src/examples/workshops/workshop-list.test.tsx b/frontend/src/examples/workshops/workshop-list.test.tsx index 2532e94d6..3dd935e8d 100644 --- a/frontend/src/examples/workshops/workshop-list.test.tsx +++ b/frontend/src/examples/workshops/workshop-list.test.tsx @@ -5,7 +5,7 @@ import { commands, userEvent } from 'vitest/browser' import { render } from 'vitest-browser-react' import type { WorkshopDto } from '@/api/generated/models/types/workshop-dto' -import { getWorkshopListQuerySearchSchema } from '@/api/generated/workshops/zod/get-workshop-list' +import { workshopForCreationDtoSchema } from '@/api/generated/models/zod/workshop-for-creation-dto' import { maxLengthOf } from '@/lib/api-contract' import { routeTree } from '@/routeTree.gen' @@ -40,7 +40,7 @@ async function renderListAt(path: string) { { method: 'GET', path: '/bff/user', status: 204 }, { method: 'GET', path: '/api/v1/workshops', headers: pagination(1, 3), body: [workshop('Page one')] }, { method: 'GET', path: '/api/v1/workshops', query: { pageNumber: '2' }, headers: pagination(2, 3), body: [workshop('Page two')] }, - { method: 'GET', path: '/api/v1/workshops', query: { search: 'Kubb' }, headers: pagination(1, 1), body: [workshop('Kubb basics')] }, + { method: 'GET', path: '/api/v1/workshops', query: { filters: 'title @=* "Kubb"' }, headers: pagination(1, 1), body: [workshop('Kubb basics')] }, ]) const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: [path] }) }) const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) @@ -82,8 +82,16 @@ test('falls back to the first page for a page that the contract refuses', async expect(router.state.location.search).toEqual({}) }) -test('takes no more search text than the contract allows', async () => { +test('falls back to the whole list for a search in the URL that is longer than a title can hold', async () => { + const tooLong = 'a'.repeat(maxLengthOf(workshopForCreationDtoSchema.shape.title) + 1) + const { screen, router } = await renderListAt(`/workshops?search=${tooLong}`) + + await expect.element(screen.getByRole('link', { name: 'Page one' })).toBeVisible() + expect(router.state.location.search).toEqual({}) +}) + +test('takes no more search text than a title can hold', async () => { const { search } = await renderListAt('/workshops') - await expect.element(search).toHaveAttribute('maxlength', String(maxLengthOf(getWorkshopListQuerySearchSchema.unwrap()))) + await expect.element(search).toHaveAttribute('maxlength', String(maxLengthOf(workshopForCreationDtoSchema.shape.title))) }) diff --git a/frontend/src/lib/querykit-text.test.ts b/frontend/src/lib/querykit-text.test.ts new file mode 100644 index 000000000..35a784863 --- /dev/null +++ b/frontend/src/lib/querykit-text.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' + +import { containsText } from '@/lib/querykit-text' + +interface Row { + title: string +} + +describe('containsText', () => { + it.each([ + ['a word', 'Paul', 'title @=* "Paul"'], + ['a percent and an underscore', '50%_off', 'title @=* "50%_off"'], + ['a quote at the end', 'quote"', 'title @=* """ quote" """'], + ['a quote at the start', '"Paul', 'title @=* """ "Paul """'], + ['a run of three quotes', 'a"""b', 'title @=* """" a"""b """"'], + ['spaces at the ends', ' Paul ', 'title @=* "Paul"'], + ])('puts text with %s in a filter that QueryKit reads as the text', (_, text, filter) => { + expect(containsText<Row>('title', text)).toBe(filter) + }) + + it.each(['', ' '])('adds no filter for the blank text "%s"', (text) => { + expect(containsText<Row>('title', text)).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/querykit-text.ts b/frontend/src/lib/querykit-text.ts new file mode 100644 index 000000000..22cc1107c --- /dev/null +++ b/frontend/src/lib/querykit-text.ts @@ -0,0 +1,24 @@ +/** + * Puts text in a QueryKit literal. QueryKit reads an unquoted value as a name, a number, or `null`, and it has no + * escape in `"..."`. So text with a quote goes in a raw literal: the text between runs of quotes that are longer than + * each run in the text, and at least three long. One space pads each side, and QueryKit removes it, so a quote at the + * start or the end of the text stays part of the text. + */ +export function quoteText(value: string): string { + if (!value.includes('"')) { + return `"${value}"` + } + const longestRun = Math.max(...(value.match(/"+/g) ?? []).map((run) => run.length)) + const delimiter = '"'.repeat(Math.max(3, longestRun + 1)) + return `${delimiter} ${value} ${delimiter}` +} + +/** + * Turns the text of a search box into a QueryKit filter that finds the rows whose field contains the text, with no + * regard to case. Blank text adds no filter. Give the DTO as `T`, so that a field that the DTO does not have fails the + * build. + */ +export function containsText<T>(field: Extract<keyof T, string>, text: string): string | undefined { + const trimmed = text.trim() + return trimmed ? `${field} @=* ${quoteText(trimmed)}` : undefined +} diff --git a/frontend/src/routes/(examples)/workshops/index.tsx b/frontend/src/routes/(examples)/workshops/index.tsx index 874d89292..ddcac7814 100644 --- a/frontend/src/routes/(examples)/workshops/index.tsx +++ b/frontend/src/routes/(examples)/workshops/index.tsx @@ -1,10 +1,8 @@ import { createFileRoute } from '@tanstack/react-router' import * as z from 'zod' -import { - getWorkshopListQueryPageNumberSchema, - getWorkshopListQuerySearchSchema, -} from '@/api/generated/workshops/zod/get-workshop-list' +import { workshopForCreationDtoSchema } from '@/api/generated/models/zod/workshop-for-creation-dto' +import { getWorkshopListQueryPageNumberSchema } from '@/api/generated/workshops/zod/get-workshop-list' import { QueryError } from '@/components/query-error' import { SearchBox } from '@/components/search-box' import { buttonVariants } from '@/components/ui/button-variants' @@ -19,13 +17,13 @@ import { useIsMobile } from '@/hooks/use-mobile' import { maxLengthOf } from '@/lib/api-contract' import { PageHeading } from '@/components/page-heading' +const searchMaxLength = maxLengthOf(workshopForCreationDtoSchema.shape.title) + const listSearchSchema = z.object({ - search: getWorkshopListQuerySearchSchema.catch(undefined), + search: z.string().max(searchMaxLength).optional().catch(undefined), page: getWorkshopListQueryPageNumberSchema.catch(undefined), }) -const searchMaxLength = maxLengthOf(getWorkshopListQuerySearchSchema.unwrap()) - export const Route = createFileRoute('/(examples)/workshops/')({ validateSearch: listSearchSchema, component: WorkshopsPage, @@ -122,7 +120,7 @@ function WorkshopRows({ list, search, page, onPageChange }: WorkshopRowsProps) { if (workshops.length === 0) { return ( <p className="text-muted-foreground"> - {search ? `No workshop has "${search.trim()}" in its title.` : 'No workshops yet. Add one with New workshop.'} + {search.trim() ? `No workshop has "${search.trim()}" in its title.` : 'No workshops yet. Add one with New workshop.'} </p> ) } diff --git a/frontend/tests/features/examples/workshops/workshops.spec.ts b/frontend/tests/features/examples/workshops/workshops.spec.ts index 2fc4d6530..33d3a4c97 100644 --- a/frontend/tests/features/examples/workshops/workshops.spec.ts +++ b/frontend/tests/features/examples/workshops/workshops.spec.ts @@ -201,7 +201,7 @@ test.describe('the workshops', () => { await workshops.searchFor('Kubb') await expect(page).toHaveURL('/workshops?search=Kubb') - expect(api.last('get', workshopPaths.list)?.query.get('search')).toBe('Kubb') + expect(api.last('get', workshopPaths.list)?.query.get('filters')).toBe('title @=* "Kubb"') expect(api.last('get', workshopPaths.list)?.query.get('pageNumber')).toBe('1') await expect(workshops.at.row('Kubb basics')).toBeVisible() }) diff --git a/tests/FullstackTemplate.FunctionalTests/FunctionalTests/TextValues/NulInReadInputTests.cs b/tests/FullstackTemplate.FunctionalTests/FunctionalTests/TextValues/NulInReadInputTests.cs index f19890aad..dc0262255 100644 --- a/tests/FullstackTemplate.FunctionalTests/FunctionalTests/TextValues/NulInReadInputTests.cs +++ b/tests/FullstackTemplate.FunctionalTests/FunctionalTests/TextValues/NulInReadInputTests.cs @@ -33,10 +33,8 @@ public class NulInReadInputTests : TestBase // example:start (ApiRoutes.Workshops.GetList, "filters"), (ApiRoutes.Workshops.GetList, "sortOrder"), - (ApiRoutes.Workshops.GetList, "search"), (ApiRoutes.Venues.GetList, "filters"), (ApiRoutes.Venues.GetList, "sortOrder"), - (ApiRoutes.Venues.GetList, "search"), // example:end ]; diff --git a/tests/FullstackTemplate.IntegrationTests/Examples/Lists/ExampleListFilterSweepTests.cs b/tests/FullstackTemplate.IntegrationTests/Examples/Lists/ExampleListFilterSweepTests.cs index fd36e7e2d..dc8b831ab 100644 --- a/tests/FullstackTemplate.IntegrationTests/Examples/Lists/ExampleListFilterSweepTests.cs +++ b/tests/FullstackTemplate.IntegrationTests/Examples/Lists/ExampleListFilterSweepTests.cs @@ -19,7 +19,7 @@ public async Task each_operator_on_each_field_of_the_workshops_runs_or_gives_a_q // Act var faults = await ListFilterSweep.FaultsAsync(typeof(WorkshopDto), (filters, sort) => - testingServiceScope.SendAsync(new GetWorkshopList.Query(WorkshopParametersDto.From(null, null, filters, sort, null)))); + testingServiceScope.SendAsync(new GetWorkshopList.Query(WorkshopParametersDto.From(null, null, filters, sort)))); // Assert faults.ShouldBeEmpty(); @@ -33,7 +33,7 @@ public async Task each_operator_on_each_field_of_the_venues_runs_or_gives_a_quer // Act var faults = await ListFilterSweep.FaultsAsync(typeof(VenueDto), (filters, sort) => - testingServiceScope.SendAsync(new GetVenueList.Query(VenueParametersDto.From(null, null, filters, sort, null)))); + testingServiceScope.SendAsync(new GetVenueList.Query(VenueParametersDto.From(null, null, filters, sort)))); // Assert faults.ShouldBeEmpty(); @@ -56,7 +56,7 @@ public async Task a_part_of_a_field_gives_a_query_input_error(string? filters, s // Act var act = () => testingServiceScope.SendAsync(new GetWorkshopList.Query( - WorkshopParametersDto.From(null, null, filters, sortOrder, null))); + WorkshopParametersDto.From(null, null, filters, sortOrder))); // Assert (await act.ShouldThrowAsync<QueryInputException>()).Parameter.ShouldBe(filters is null ? "sortOrder" : "filters"); diff --git a/tests/FullstackTemplate.IntegrationTests/Examples/Venues/VenueListQueryTests.cs b/tests/FullstackTemplate.IntegrationTests/Examples/Venues/VenueListQueryTests.cs index a55249c84..bc6c751ce 100644 --- a/tests/FullstackTemplate.IntegrationTests/Examples/Venues/VenueListQueryTests.cs +++ b/tests/FullstackTemplate.IntegrationTests/Examples/Venues/VenueListQueryTests.cs @@ -2,15 +2,15 @@ namespace FullstackTemplate.IntegrationTests.Examples.Venues; using FullstackTemplate.Server.Examples.Venues.Dtos; using FullstackTemplate.Server.Examples.Venues.Features; -using FullstackTemplate.Server.Exceptions; using FullstackTemplate.SharedTestHelpers.EntityGraphs; using FullstackTemplate.SharedTestHelpers.Examples.EntityGraphs; +using FullstackTemplate.SharedTestHelpers.Utilities; using Shouldly; public class VenueListQueryTests : TestBase { [Test] - public async Task a_search_finds_the_names_that_contain_the_text_with_no_regard_to_case_and_a_percent_as_plain_text() + public async Task a_name_filter_finds_the_names_that_contain_the_text_with_no_regard_to_case_and_a_percent_as_plain_text() { // Arrange var testingServiceScope = new TestingServiceScope(); @@ -24,28 +24,18 @@ await testingServiceScope.StartGraph(out _) .BuildAsync(); // Act - var found = await testingServiceScope.SendAsync(new GetVenueList.Query( - VenueParametersDto.From(null, null, null, null, $" hall {marker.ToUpperInvariant()} "))); - var percent = await testingServiceScope.SendAsync(new GetVenueList.Query( - VenueParametersDto.From(null, null, null, null, $"{marker} 50%"))); + var found = await NamesContainingAsync(testingServiceScope, $"hall {marker.ToUpperInvariant()}"); + var percent = await NamesContainingAsync(testingServiceScope, $"{marker} 50%"); // Assert - found.Select(v => v.Name).ShouldBe([$"North Hall {marker}", $"South Hall {marker}"]); - percent.Select(v => v.Name).ShouldBe([$"{marker} 50% full"]); + found.ShouldBe([$"North Hall {marker}", $"South Hall {marker}"]); + percent.ShouldBe([$"{marker} 50% full"]); } - [Test] - public async Task a_search_longer_than_its_maximum_gives_a_query_input_error() + private static async Task<List<string>> NamesContainingAsync(TestingServiceScope scope, string text) { - // Arrange - var testingServiceScope = new TestingServiceScope(); - var search = new string('a', VenueParametersDto.SearchMaxLength + 1); - - // Act - var act = () => testingServiceScope.SendAsync(new GetVenueList.Query( - VenueParametersDto.From(null, null, null, null, search))); - - // Assert - (await act.ShouldThrowAsync<QueryInputException>()).Parameter.ShouldBe("search"); + var page = await scope.SendAsync(new GetVenueList.Query( + VenueParametersDto.From(null, null, $"name @=* {QueryKitText.Quote(text)}", null))); + return page.Select(v => v.Name).ToList(); } } diff --git a/tests/FullstackTemplate.IntegrationTests/Examples/Workshops/WorkshopListQueryTests.cs b/tests/FullstackTemplate.IntegrationTests/Examples/Workshops/WorkshopListQueryTests.cs index 70dab569c..7187faccf 100644 --- a/tests/FullstackTemplate.IntegrationTests/Examples/Workshops/WorkshopListQueryTests.cs +++ b/tests/FullstackTemplate.IntegrationTests/Examples/Workshops/WorkshopListQueryTests.cs @@ -5,6 +5,7 @@ namespace FullstackTemplate.IntegrationTests.Examples.Workshops; using FullstackTemplate.Server.Exceptions; using FullstackTemplate.SharedTestHelpers.EntityGraphs; using FullstackTemplate.SharedTestHelpers.Examples.EntityGraphs; +using FullstackTemplate.SharedTestHelpers.Utilities; using Shouldly; public class WorkshopListQueryTests : TestBase @@ -17,16 +18,16 @@ public class WorkshopListQueryTests : TestBase [Arguments("50%", "Yard 50% full")] [Arguments("a_b", "a_b")] [Arguments(@"c\d", @"c\d")] - [Arguments(" A_B ", "a_b")] - public async Task a_search_matches_a_percent_an_underscore_or_a_backslash_as_plain_text(string search, string match) + [Arguments("A_B", "a_b")] + public async Task a_title_filter_matches_a_percent_an_underscore_or_a_backslash_as_plain_text(string text, string match) { // Arrange var testingServiceScope = new TestingServiceScope(); var venueId = await AddWorkshopsAsync(testingServiceScope); // Act - var found = await testingServiceScope.SendAsync(new GetWorkshopList.Query( - WorkshopParametersDto.From(null, null, $"venueId == \"{venueId}\"", null, search))); + var found = await testingServiceScope.SendAsync(new GetWorkshopList.Query(WorkshopParametersDto.From( + null, null, $"venueId == \"{venueId}\" && title @=* {QueryKitText.Quote(text)}", null))); // Assert found.Select(w => w.Title).ShouldBe([match]); @@ -41,7 +42,7 @@ public async Task the_list_sorts_by_the_start_and_gives_each_row_its_actions() // Act var page = await testingServiceScope.SendAsync(new GetWorkshopList.Query( - WorkshopParametersDto.From(1, 4, $"venueId == \"{venueId}\"", null, null))); + WorkshopParametersDto.From(1, 4, $"venueId == \"{venueId}\"", null))); // Assert page.TotalCount.ShouldBe(Titles.Length); @@ -52,32 +53,17 @@ public async Task the_list_sorts_by_the_start_and_gives_each_row_its_actions() [Test] [Arguments("a\0b")] [Arguments("\uD800")] - public async Task a_search_with_a_character_that_postgres_cannot_store_gives_a_query_input_error(string search) - { - // Arrange - var testingServiceScope = new TestingServiceScope(); - - // Act - var act = () => testingServiceScope.SendAsync(new GetWorkshopList.Query( - WorkshopParametersDto.From(null, null, null, null, search))); - - // Assert - (await act.ShouldThrowAsync<QueryInputException>()).Parameter.ShouldBe("search"); - } - - [Test] - public async Task a_search_longer_than_its_maximum_gives_a_query_input_error() + public async Task a_title_filter_with_a_character_that_postgres_cannot_store_gives_a_query_input_error(string text) { // Arrange var testingServiceScope = new TestingServiceScope(); - var search = new string('a', WorkshopParametersDto.SearchMaxLength + 1); // Act var act = () => testingServiceScope.SendAsync(new GetWorkshopList.Query( - WorkshopParametersDto.From(null, null, null, null, search))); + WorkshopParametersDto.From(null, null, $"title @=* {QueryKitText.Quote(text)}", null))); // Assert - (await act.ShouldThrowAsync<QueryInputException>()).Parameter.ShouldBe("search"); + (await act.ShouldThrowAsync<QueryInputException>()).Parameter.ShouldBe("filters"); } public static IEnumerable<(string, string[])> FiltersThatTheFilterBuilderWrites => @@ -110,7 +96,7 @@ public async Task a_filter_that_the_filter_builder_writes_finds_its_text(string // Act var found = await testingServiceScope.SendAsync(new GetWorkshopList.Query( - WorkshopParametersDto.From(null, null, $"venueId == \"{venueId}\" && {filter}", null, null))); + WorkshopParametersDto.From(null, null, $"venueId == \"{venueId}\" && {filter}", null))); // Assert found.Select(w => w.Title).ShouldBe(matches, ignoreOrder: true);