@nocobase/app-skills 0.1.0-beta.56 → 0.1.0-beta.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/nocobase-app-development/references/frontend/references/api.md +5 -2
- package/skills/nocobase-app-development/references/frontend/references/testing.md +67 -0
- package/skills/nocobase-app-development/references/http-api.md +2 -0
- package/skills/nocobase-app-development/references/server-routes.md +5 -1
package/package.json
CHANGED
|
@@ -172,6 +172,7 @@ This handbook's project endpoints are called like this (`id` is the record id, `
|
|
|
172
172
|
|
|
173
173
|
- Encode every id with `encodeURIComponent` before putting it into `path`; ids are strings and may come from a URL parameter or user input.
|
|
174
174
|
- A list takes `q` for search, `orderBy` for ordering, and `page` with `pageSize` (20 by default, at most 100), and answers `{ data, meta: { page, pageSize, total } }`, typed `ProjectList` in [`example/types.md`](example/types.md). A feed or log pages with `pageSize` and `pageToken` instead, and its `meta` carries `nextPageToken` until the last page.
|
|
175
|
+
- Read row summaries with the list response or one batch request for the visible ids, never a child-resource request from every row: client N+1 multiplies network and server work as the page grows. Right: render `row.linkCount` supplied by the list; wrong: each row calls `projects/{id}/links` just to count links. The server batches that summary as [server routes](../../server-routes.md#lists-and-statistics-a-fixed-number-of-queries) describes.
|
|
175
176
|
|
|
176
177
|
### Parameters and response bodies
|
|
177
178
|
|
|
@@ -312,7 +313,7 @@ Other points:
|
|
|
312
313
|
|
|
313
314
|
When realtime events refresh what a page shows:
|
|
314
315
|
|
|
315
|
-
- An event that names items refreshes those items: gather the ids of a burst (a few hundred milliseconds), read only those rows, keep one such request in flight, and merge the answer into what the page holds. Read the whole list again only when its membership changed (an item joined or left it, or moved between its groups) or the event names nothing.
|
|
316
|
+
- An event that names items refreshes those items: use its changed fields to select affected sections, gather the ids of a burst (a few hundred milliseconds), read only those rows, keep one such request in flight, and merge the answer into what the page holds. Right: a `name` change refreshes the named row but leaves a status chart alone; wrong: every event refreshes the row, history and every chart. Read the whole list again only when its membership changed (an item joined or left it, or moved between its groups) or the event names nothing.
|
|
316
317
|
- Do not read a whole list or overview again on every event.
|
|
317
318
|
- Recompute a chart's figures at most every few seconds while it is visible, and not at all while the page is hidden; or update only the figure the event affects.
|
|
318
319
|
- Read nothing for a page that is not shown; read it when it is shown again.
|
|
@@ -323,7 +324,9 @@ When realtime events refresh what a page shows:
|
|
|
323
324
|
- Keep request keys stable: build them from the parameters that decide the data, not from values that change on every render or tick, such as the current time, or each change starts a new request.
|
|
324
325
|
- Be careful with data loaded by components mounted on every page, such as navigation or a header badge: they run on every page and in every open tab, so they usually read a small fact rather than a list.
|
|
325
326
|
|
|
326
|
-
|
|
327
|
+
Test a complete event-driven refresh cycle with a request spy and an explicit completion signal, excluding the initial load: assert an upper bound on reads per event per open tab, including any follow-up read. Right: `expect(refreshRequests.length).toBeLessThanOrEqual(1)` after the cycle completes and the changed row is visible; wrong: asserting only that a request occurred or that the refresh finished quickly. Counts catch duplicate topics and per-row reads without depending on machine speed.
|
|
328
|
+
|
|
329
|
+
The server side of these reads is in [list and statistics rules](../../server-routes.md#lists-and-statistics-a-fixed-number-of-queries); normalized log measurements are in [frequently called endpoints](../../server-routes.md#frequently-called-endpoints).
|
|
327
330
|
|
|
328
331
|
## Error handling
|
|
329
332
|
|
|
@@ -89,6 +89,57 @@ Use the page's actual translated labels and response shape. Node identity is use
|
|
|
89
89
|
|
|
90
90
|
jsdom verifies DOM continuity and request behavior, not layout or visible animation. In the actual application browser, exercise the affected flow from its entry through loading, completion and closing, with controlled slow responses or failures where relevant. Observe layout, animation, focus and scroll throughout; inspect animation events or computed animation when checking entrance replay. A final screenshot or CSS class assertion is insufficient. Distinguish component or synthetic fixture checks from actual application checks, which also cover routing, permissions and business APIs. Follow the workflow's session rules and report unavailable browser checks as unverified.
|
|
91
91
|
|
|
92
|
+
### Browser stability
|
|
93
|
+
|
|
94
|
+
Assert the final result a user sees with auto-retrying locators; do not wait for an uncontrolled intermediate state or sleep a fixed duration, because a fast response can skip that state and a slow one can outlast the sleep. Right: `await expect(page.getByText('Project saved')).toBeVisible()`; wrong: waiting for a brief spinner before asserting success, or `await page.waitForTimeout(1000)`. Controlled pending-state tests above deliberately hold the response, so their loading assertions are deterministic.
|
|
95
|
+
|
|
96
|
+
Retry geometry assertions with `expect.poll` or `toPass` until the intended layout settles; one `boundingBox()` snapshot can capture an animation frame. For example, with a `panel` locator and the expected content edge `contentRight`:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
// Right: re-read geometry on each attempt.
|
|
100
|
+
await expect
|
|
101
|
+
.poll(async () => (await panel.boundingBox())?.x)
|
|
102
|
+
.toBeGreaterThanOrEqual(contentRight);
|
|
103
|
+
// Wrong: const box = await panel.boundingBox(); expect(box!.x).toBe(600);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
After navigation or opening an overlay, wait for an existing control's interactive signal before clicking: visible markup or a changed URL can precede loaded controls and the end of an opening transition. Right: `await expect(saveButton).toBeEnabled(); await saveButton.click()` when Save is enabled after loading, or `await expect(nameInput).toBeFocused()` when focus is placed after opening; wrong: click immediately after `page.goto()` or seeing the dialog shell. Use the application's existing enabled state or focus behavior rather than adding a test-only ready marker or a fixed wait.
|
|
107
|
+
|
|
108
|
+
Register a request interceptor once per page-scoped test, let subsequent traffic through with `route.fallback()`, and release every held request in `finally`: failed assertions otherwise leave requests blocked and hang teardown. Do not call `unroute` or replace a handler while it is running. This schematic gate holds all matching requests; `appUrl` is the running application's entry URL:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const gate = Promise.withResolvers<void>();
|
|
112
|
+
const handlers = new Set<Promise<void>>();
|
|
113
|
+
let holding = true;
|
|
114
|
+
await page.route('**/api/projects*', (route) => {
|
|
115
|
+
const done = (async () => {
|
|
116
|
+
if (holding) await gate.promise;
|
|
117
|
+
await route.fallback();
|
|
118
|
+
})();
|
|
119
|
+
handlers.add(done);
|
|
120
|
+
return done.finally(() => {
|
|
121
|
+
handlers.delete(done);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
try {
|
|
125
|
+
await page.goto(appUrl);
|
|
126
|
+
// Exercise the controlled pending state, then allow final results.
|
|
127
|
+
holding = false;
|
|
128
|
+
gate.resolve();
|
|
129
|
+
await expect(page.getByRole('heading', { name: 'Projects' })).toBeVisible();
|
|
130
|
+
} finally {
|
|
131
|
+
holding = false;
|
|
132
|
+
gate.resolve();
|
|
133
|
+
await Promise.allSettled([...handlers]);
|
|
134
|
+
}
|
|
135
|
+
// Keep the fallback handler until the page fixture closes.
|
|
136
|
+
// Wrong: page.unroute(pattern) while its handler is still awaiting the gate.
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Use `Promise.allSettled` during cleanup so a fallback failure after the page closes does not replace the original assertion failure.
|
|
140
|
+
|
|
141
|
+
Investigate intermittent failures as possible product races first: if a late response overwrites the current record, fix response ownership in the product and keep a regression test. Right: reproduce with controlled response ordering and correct the product; wrong: add retries, increase timeouts or weaken the assertion so the race passes unnoticed.
|
|
142
|
+
|
|
92
143
|
## Running tests
|
|
93
144
|
|
|
94
145
|
Run the related test files with the application's matching React configuration, then lint them. Inspect its tsconfig includes before claiming the tests were typechecked; many templates exclude Vitest tests from their build configs. The complete client example uses `--config vitest.client.config.ts`:
|
|
@@ -108,3 +159,19 @@ End-to-end tests run against a running application. `playwright.config.ts` sets
|
|
|
108
159
|
```bash
|
|
109
160
|
pnpm test:e2e
|
|
110
161
|
```
|
|
162
|
+
|
|
163
|
+
Each case creates and cleans up its own records and can run alone or in any order; depending on an earlier test's data makes failures order-dependent. Right: create a uniquely named project in that case's fixture; wrong: edit the project created by the previous case. Parallel workers must not write a shared state file: use a per-worker path such as `storage/e2e/auth-${workerIndex}.json` for mutable authentication state. A single global setup may produce a read-only authentication snapshot shared by independent contexts; cases must not overwrite it or mutate shared account settings.
|
|
164
|
+
|
|
165
|
+
To find unstable cases, run the whole suite N times on the same runner, then use `--repeat-each` for suspects: isolated repetition alone misses interference from other cases. Keep each run's raw reporter output, including full `testId`, project, repeat index, retry and error/trace attachments; abbreviated titles lose the identity needed to compare failures. For example, with an authenticated application already running and `N` set to the desired suite count:
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
mkdir -p storage/e2e/results
|
|
169
|
+
for run in $(seq 1 "$N"); do
|
|
170
|
+
PLAYWRIGHT_BLOB_OUTPUT_FILE="storage/e2e/results/suite-$run.zip" \
|
|
171
|
+
pnpm test:e2e --reporter=blob --retries=0
|
|
172
|
+
done
|
|
173
|
+
PLAYWRIGHT_BLOB_OUTPUT_FILE=storage/e2e/results/suspect.zip \
|
|
174
|
+
pnpm test:e2e tests/playwright/projects.test.ts --repeat-each=20 --reporter=blob --retries=0
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Right: retain all blob reports (which carry full test ids) and their failures, plus the tested commit and command; wrong: rerun until green and keep only a title-only summary. Repetition diagnoses failures; it is not a retry policy for accepting them.
|
|
@@ -61,6 +61,8 @@ There are two pagination styles, and a list uses one of them:
|
|
|
61
61
|
|
|
62
62
|
`pageSize` defaults to 20 and is capped at 100; a route that needs a larger cap keeps it and says why in a comment. Search is `q`, ordering is `orderBy`.
|
|
63
63
|
|
|
64
|
+
When a filter selects several values of the same field, accept them in one request and document and validate the encoding (for example, comma-separated enum values with OR semantics): splitting by value multiplies requests and makes pagination and totals inconsistent. Right: `GET /orders?status=open,closed`; wrong: separate `status=open` and `status=closed` requests merged in the client. Reject unknown values and bound the number of values through `apiValidator()` like any other input.
|
|
65
|
+
|
|
64
66
|
A bounded configuration list, such as providers, roles, templates or catalogs, may skip paging, but it still answers `{ data, meta }` with at least `meta.total`. Every other list pages. `meta` may carry fields beyond the standard ones when a list has more to say about itself.
|
|
65
67
|
|
|
66
68
|
Data formats:
|
|
@@ -240,12 +240,13 @@ A route that answers many rows or figures reads them with a fixed number of quer
|
|
|
240
240
|
- Read each kind of data once for all rows: one query with `IN (...)` over the row ids, then join the results in memory. Never call a per-item function or Repository read inside a loop or a `Promise.all` over rows.
|
|
241
241
|
- When per-item database work genuinely cannot be batched, bound its concurrency to a small number rather than starting one query per item at once: an unbounded `Promise.all` can exhaust the connection pool and stall every other request, not just this one.
|
|
242
242
|
- A list row carries only what the row shows. Expensive per-item work — diagnostics, "why is this waiting", full histories — belongs to the item's own detail endpoint, which the client usually reads when a detail view opens. When you add a field to a list response, check how much it adds to the response size across a full page of rows.
|
|
243
|
+
- A detail endpoint computes only what its consumer displays. Put expensive optional sections behind a separate endpoint or an explicit, validated option, and do not compute them before checking the option: unused enrichment can dominate a frequently refreshed detail read. Right: `includeProgress ? await computeProgress(id) : undefined`; wrong: always computing progress and then dropping it from the browser response. A caller hint in a request log is not a permission or a substitute for the declared response contract.
|
|
243
244
|
- A component that needs one small fact, such as whether the viewer follows an item, gets a small endpoint answering that fact rather than reading a whole list or overview.
|
|
244
245
|
- Aggregate in the database: `COUNT`, `SUM`, `GROUP BY` through the Repository's `count`/`groupBy` or the query builder. Never load rows to count or sum them in JavaScript.
|
|
245
246
|
- One chart is one request, so charts load, fail, refresh and cache on their own. Each chart's request computes its figures with a fixed number of aggregate queries: one `GROUP BY` day, not a query per day or per item.
|
|
246
247
|
- Bound every statistic by a time range or a limit. A column a large table is filtered or grouped by needs an index — see [migrations](migrations.md).
|
|
247
248
|
- An aggregate that is expensive and read often is cached briefly with the application's cache (`cachingToken` from `@nocobase/app-server/caching`) rather than recomputed per request.
|
|
248
|
-
- Test it
|
|
249
|
+
- Test it with query-count upper bounds at small and large row/group counts, not elapsed time: machine speed can hide duplicated work. Right: `expect(queryCount).toBeLessThanOrEqual(3)` for both ten and a thousand rows; wrong: `expect(elapsedMs).toBeLessThan(100)`. See [testing](testing.md#what-to-test-by-change).
|
|
249
250
|
|
|
250
251
|
The browser side — refreshing such a list or chart from realtime events — is in [client API requests](frontend/references/api.md#keeping-lists-and-charts-live).
|
|
251
252
|
|
|
@@ -256,6 +257,9 @@ An endpoint called on a timer — polling, a heartbeat, a status badge every ope
|
|
|
256
257
|
- Usually keep it read-only, without writes or a transaction. Work that has to write, such as recording last-seen times or cleaning up, can often move to a less frequent place: a scheduled job (see [services and jobs](services-and-jobs.md#work-that-runs-on-a-schedule)), or a write only when the value actually changed.
|
|
257
258
|
- Read-only code usually needs no transaction, here or anywhere else. A transaction holds a connection for its whole duration and can make reads cost more; use one only for writes that must succeed or fail together.
|
|
258
259
|
- Prefer answering a small fact over a list or overview, as the section above describes, and consider caching it briefly when many clients ask the same question.
|
|
260
|
+
- Publish one realtime signal per domain change, with affected ids and changed fields (within the topic's authorization scope), rather than publishing the same change on several topics: a page subscribed to all of them otherwise multiplies its reads. Right: one `orders` event with `{ ids: [id], changed: ['status'] }`; wrong: that same change on `orders`, `orderDetails` and `orderStats`. Consumers use the payload as described in [client refresh rules](frontend/references/api.md#keeping-lists-and-charts-live).
|
|
261
|
+
|
|
262
|
+
Measure before and after with request logs on the same dataset and action sequence. Group completion entries by `req.method`, route template `req.path`, safe `req.query` and `req.caller` to separate filters and browser, CLI and runner traffic; caller labels are transport hints, not authenticated identities. Query logging omits unsafe values, so do not infer an absent filter or add raw URLs, secrets or free text to recover it. Compare queries per request and requests per event per open tab, accounting separately for initial loads and background polling: time-window totals change with tab count and activity. Right: 30 browser reads / 5 events / 2 subscribed tabs = 3 reads per event per tab; wrong: claiming an improvement because one minute had fewer total requests. Lock the resulting request bound in the [frontend tests](frontend/references/api.md#keeping-lists-and-charts-live).
|
|
259
263
|
|
|
260
264
|
## Keep the layers apart
|
|
261
265
|
|