@ahoo-wang/wow-react 10.0.0-alpha.3 → 10.0.0-alpha.5

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/README.md CHANGED
@@ -25,7 +25,7 @@ pnpm add react react-dom @ahoo-wang/fetcher @ahoo-wang/fetcher-eventstream \
25
25
  `@ahoo-wang/fetcher-eventstream` is a peer of `@ahoo-wang/wow-client`, not of
26
26
  this package.
27
27
 
28
- The version follows Wow, so a minor release may contain breaking changes: keep the Wow packages on one minor with `save-prefix=~` or `--save-exact`, as [version ranges](https://wow.ahoo.me/guide/typescript/compatibility#version-ranges) explains.
28
+ The version follows Wow, so a minor release may contain breaking changes: keep the Wow packages on one minor with `save-prefix=~` or `--save-exact`, as [version ranges](https://wow.ahoo.me/typescript/compatibility#version-ranges) explains.
29
29
 
30
30
  The hooks run their own request state machine: `@ahoo-wang/fetcher-react` is
31
31
  not needed, and neither is `@ahoo-wang/fetcher-wow`.
@@ -36,28 +36,26 @@ The package ships ES modules only. CommonJS code on Node.js 22.12+ can still
36
36
 
37
37
  ## With a query client
38
38
 
39
- The `use*Query` hooks take an `execute` function. A query client method —
40
- `SnapshotQueryClient` of `@ahoo-wang/wow-client`, or the one a generated
41
- `…QueryClientFactory` creates — has exactly the `(query, attributes, abort)`
42
- shape `execute` takes, so the client supplies the URL, the headers and the
43
- response handling, and nothing is hand-written. The clients bind their
44
- methods, so `execute: client.pagedState` works as is; a method of an object
45
- of your own needs `.bind(object)` or an arrow function:
39
+ The `use*Query` hooks take an `execute` function: the query and the request
40
+ options of the run, its `signal` included. A query client of
41
+ `@ahoo-wang/wow-client` — a generated `…SnapshotQueryClient`, or a
42
+ `QueryModelClient` — takes exactly those as its last parameters, so the client
43
+ supplies the route, the headers and the response handling, and nothing is
44
+ hand-written:
46
45
 
47
46
  ```tsx
48
- import {
49
- filter,
50
- pagedQuery,
51
- type SnapshotQueryClient,
47
+ import type {
48
+ SnapshotQueryClient,
49
+ SnapshotRecord,
52
50
  } from '@ahoo-wang/wow-client';
51
+ import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';
53
52
  import { usePagedQuery } from '@ahoo-wang/wow-react';
54
53
 
55
54
  interface OrderState {
56
- id: string;
57
55
  status: string;
58
56
  }
59
- // The fields a query may name; a generated client exports this type.
60
- type OrderFields = 'aggregateId' | 'state.status';
57
+ // The state fields a query may name; a generated client exports this type.
58
+ type OrderFields = 'state.status';
61
59
 
62
60
  export function PaidOrders({
63
61
  client,
@@ -66,12 +64,15 @@ export function PaidOrders({
66
64
  client: SnapshotQueryClient<OrderState, OrderFields>;
67
65
  page: number;
68
66
  }) {
69
- const { result, loading, error } = usePagedQuery<OrderState, OrderFields>({
67
+ const { result, loading, error } = usePagedQuery<
68
+ SnapshotRecord<OrderState>,
69
+ OrderFields
70
+ >({
70
71
  query: pagedQuery({
71
72
  filter: filter.eq('state.status', 'PAID'),
72
73
  pagination: { index: page, size: 20 },
73
74
  }),
74
- execute: client.pagedState,
75
+ execute: (query, options) => client.paged(query, options),
75
76
  });
76
77
 
77
78
  if (error) return <p role="alert">Unable to load orders</p>;
@@ -79,7 +80,7 @@ export function PaidOrders({
79
80
  return (
80
81
  <ul>
81
82
  {result.list.map(order => (
82
- <li key={order.id}>{order.status}</li>
83
+ <li key={order.aggregateId}>{order.state.status}</li>
83
84
  ))}
84
85
  </ul>
85
86
  );
@@ -88,38 +89,42 @@ export function PaidOrders({
88
89
 
89
90
  Pass the client's fields type as the second type argument, as above: a
90
91
  generated client's fields are narrower than `string`, and TypeScript does not
91
- infer them from `execute` once the first type argument is written. Hand
92
- `abortController` on: a newer query, `abort()`, `reset()` and an unmount then
93
- cancel the request. A snapshot query filters the snapshot document, whose state lives
94
- under `state`, so a state field is `state.status`, not `status`.
92
+ infer them from `execute` once the first type argument is written. Hand the
93
+ options on: a newer query, `abort()`, `reset()` and an unmount then cancel the
94
+ request. Hand a method over through an arrow function, as above: a method
95
+ passed alone loses its `this`. A snapshot query filters the snapshot record,
96
+ whose state lives under `state`, so a state field is `state.status`, not
97
+ `status`. `requestOptions` adds the scope, the space or more headers to every
98
+ run.
95
99
 
96
- Aggregations have no hook yet; a generic `useQuery` and aggregation hooks are
97
- planned for 9.3. Until then call `client.aggregate` in an effect and abort it on
98
- cleanup, as the
99
- [reference page](https://wow.ahoo.me/reference/typescript/wow-react/#aggregations)
100
- shows.
100
+ Aggregations have no hook yet. Call `client.aggregate(query, { signal })` in
101
+ an effect with an `AbortController` and abort it on cleanup.
101
102
 
102
103
  Cursor queries have no hook yet either. Run one through `useSingleQuery`, with
103
104
  the page as the result: pass `CursorPage<R>` and `CursorQuery<Fields>` as the
104
- type arguments and `client.cursorState` (or `client.cursor`) as `execute`, and
105
- move to the next page with `setQuery({ ...query, cursor: result.nextCursor })`
106
- while `nextCursor` is not `null`.
105
+ type arguments and `client.cursor` as `execute`, and move to the next page with
106
+ `setQuery({ ...query, cursor: result.nextCursor })` while `nextCursor` is not
107
+ `null`.
107
108
 
108
109
  ## With an endpoint URL
109
110
 
110
- The `useFetcher*Query` hooks POST the query to a URL through a Fetcher instead:
111
+ The `useFetcher*Query` hooks POST the query to a query route through a
112
+ Fetcher instead:
111
113
 
112
114
  ```tsx
113
115
  import { Fetcher } from '@ahoo-wang/fetcher';
114
- import { filter, pagedQuery } from '@ahoo-wang/wow-client';
116
+ import type { SnapshotRecord } from '@ahoo-wang/wow-client';
117
+ import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';
115
118
  import { useFetcherPagedQuery } from '@ahoo-wang/wow-react';
116
119
 
117
- const fetcher = new Fetcher({ baseURL: 'https://api.example.com/' });
120
+ const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
118
121
 
119
122
  export function PaidOrders() {
120
- const { result, loading, error } = useFetcherPagedQuery<OrderState>({
123
+ const { result, loading, error } = useFetcherPagedQuery<
124
+ SnapshotRecord<OrderState>
125
+ >({
121
126
  fetcher,
122
- url: 'order/snapshot/paged/state',
127
+ url: '/shop/order/snapshot/query',
123
128
  initialQuery: pagedQuery({
124
129
  filter: filter.eq('state.status', 'PAID'),
125
130
  pagination: { index: 1, size: 20 },
@@ -130,10 +135,10 @@ export function PaidOrders() {
130
135
  ```
131
136
 
132
137
  `fetcher` is a Fetcher or the name of a registered one; without it the default
133
- Fetcher sends the request. The snapshot routes of an aggregate are
134
- `{aggregate}/snapshot/{single|list|paged}[/state]` and
135
- `{aggregate}/snapshot/count`, behind the context alias and the owner or tenant
136
- path when the aggregate has them.
138
+ Fetcher sends the request. An aggregate's snapshots are queried at
139
+ `/{context}/{aggregate}/snapshot/query`, its events at
140
+ `/{context}/{aggregate}/events/query`; the hook names the operation (`single`,
141
+ `list`, `paged`, `count`) in the query's `kind`.
137
142
 
138
143
  A request is identified by `url` and the Fetcher: a named Fetcher by its name,
139
144
  an unnamed one by its `baseURL`. Two unnamed Fetchers with the same `baseURL`
@@ -144,32 +149,32 @@ name, or pass the name of a registered Fetcher, to tell them apart.
144
149
  ## Streaming a list
145
150
 
146
151
  `useListStreamQuery` and `useFetcherListStreamQuery` read a list as
147
- server-sent events and keep the rows as they arrive. `listQuery()` sends a
148
- `limit` only when given one: Wow 9.1.5 and later then apply their default list
149
- size, while Wow 8.11 to 9.1.3 reject the query with HTTP 400, so pass `limit`
150
- for those servers.
152
+ server-sent events and keep the rows as they arrive. A stream the service
153
+ cuts off is resumed where it stopped, as wow-client's `listStream` does.
151
154
 
152
155
  ```tsx
153
- import { filter, listQuery } from '@ahoo-wang/wow-client';
156
+ import type { SnapshotRecord } from '@ahoo-wang/wow-client';
157
+ import { filter, listQuery } from '@ahoo-wang/wow-client/dsl';
154
158
  import { useFetcherListStreamQuery } from '@ahoo-wang/wow-react';
155
159
 
156
160
  export function PaidOrderFeed() {
157
- const { items, done, loading, error, abort } =
158
- useFetcherListStreamQuery<OrderState>({
159
- fetcher,
160
- url: 'order/snapshot/list/state',
161
- initialQuery: listQuery({
162
- filter: filter.eq('state.status', 'PAID'),
163
- limit: 100,
164
- }),
165
- });
161
+ const { items, done, loading, error, abort } = useFetcherListStreamQuery<
162
+ SnapshotRecord<OrderState>
163
+ >({
164
+ fetcher,
165
+ url: '/shop/order/snapshot/query',
166
+ initialQuery: listQuery({
167
+ filter: filter.eq('state.status', 'PAID'),
168
+ limit: 100,
169
+ }),
170
+ });
166
171
 
167
172
  if (error) return <p role="alert">{error.message}</p>;
168
173
  return (
169
174
  <>
170
175
  <ul>
171
176
  {items.map(order => (
172
- <li key={order.id}>{order.id}</li>
177
+ <li key={order.aggregateId}>{order.state.status}</li>
173
178
  ))}
174
179
  </ul>
175
180
  {loading && <button onClick={abort}>Stop</button>}
@@ -184,15 +189,15 @@ export function PaidOrderFeed() {
184
189
  | `items` | The rows of the current query received so far, in order. A new query starts empty; `reset()` empties it. |
185
190
  | `done` | The stream ended normally: `items` holds every row. The same as `status === 'success'`. |
186
191
  | `loading` | From the request until the stream ends, fails or is aborted. |
187
- | `error` | A failed request (`FetcherError`), or a `WowError` with the server's `errorCode` when the server sends an error event midway. |
192
+ | `error` | The `WowProblemError` of a failed request, or of the error event the service sends midway. |
188
193
  | `abort()` | Stops the stream and keeps the rows received. `reset()` stops it and empties `items`. `execute()` runs the current query again. |
189
194
 
190
195
  The hook owns the stream: it reads it, renders the rows at most about once a
191
196
  frame (every 16 ms) however many arrive, and cancels it when a newer query starts, on `abort()` or
192
197
  `reset()`, and on unmount. Components never hold a reader, so the hook is safe
193
198
  under StrictMode. `useFetcherListStreamQuery` sends `Accept: text/event-stream`,
194
- which a Wow server needs to answer with a stream; with `useListStreamQuery`,
195
- pass a client's `listStream` or `listStateStream` as `execute`.
199
+ which a Wow service needs to answer with a stream; with `useListStreamQuery`,
200
+ pass a client's `listStream` as `execute`.
196
201
 
197
202
  ## State and errors
198
203
 
@@ -221,15 +226,18 @@ and `QueryExecutor`. `status` is the plain string union
221
226
  can write a literal.
222
227
 
223
228
  `error` is typed `Error` unless you pass the `E` type argument: a failed
224
- request rejects with a `FetcherError`, an error event in a stream with a
225
- `WowError`, and your own `execute` with whatever it throws. `toWowError` from
226
- `@ahoo-wang/wow-client` reads the server's `ErrorInfo` from a failed request:
229
+ request, and an error event in a stream, reject with wow-client's
230
+ `WowProblemError`, and your own `execute` with whatever it throws. The problem
231
+ carries the service's `code` and its `status`:
227
232
 
228
233
  ```ts
229
- import { ErrorCodes, toWowError } from '@ahoo-wang/wow-client';
234
+ import { FrameworkErrorCodes, WowProblemError } from '@ahoo-wang/wow-client';
230
235
 
231
- const wowError = await toWowError(error);
232
- if (wowError?.errorCode === ErrorCodes.NOT_FOUND) {
236
+ declare const error: unknown;
237
+ if (
238
+ error instanceof WowProblemError &&
239
+ error.code === FrameworkErrorCodes.AGGREGATE_NOT_FOUND
240
+ ) {
233
241
  // …
234
242
  }
235
243
  ```
@@ -240,22 +248,18 @@ if (wowError?.errorCode === ErrorCodes.NOT_FOUND) {
240
248
  | ------------------------------------------------- | ----------------------------- | ----------------------------------- |
241
249
  | `useSingleQuery`, `useFetcherSingleQuery` | `singleQuery(…)` | `result`: one item |
242
250
  | `useListQuery`, `useFetcherListQuery` | `listQuery(…)` | `result`: the rows |
243
- | `usePagedQuery`, `useFetcherPagedQuery` | `pagedQuery(…)` | `result`: `{ total, list }` |
244
- | `useCountQuery`, `useFetcherCountQuery` | a `filter.*` expression | `result`: the count |
251
+ | `usePagedQuery`, `useFetcherPagedQuery` | `pagedQuery(…)` | `result`: `{ total, exact, list }` |
252
+ | `useCountQuery`, `useFetcherCountQuery` | `{ filter, limit? }` | `result`: `{ count, exact }` |
245
253
  | `useListStreamQuery`, `useFetcherListStreamQuery` | `listQuery(…)`, as SSE events | `items` as they arrive, then `done` |
246
254
 
247
- The query types default to the `filter` API of `@ahoo-wang/wow-client`. Each
248
- hook also accepts the deprecated Condition queries of
249
- `@ahoo-wang/wow-client/legacy`, which Wow 8.10 servers need; that overload goes
250
- in v10.
255
+ The queries are built with the DSL of `@ahoo-wang/wow-client/dsl`.
251
256
 
252
257
  Moved from `@ahoo-wang/fetcher-react` (its Wow hooks) in Wow 9; the version
253
258
  follows Wow.
254
259
 
255
260
  ## Documentation
256
261
 
257
- - [TypeScript guide](https://wow.ahoo.me/guide/typescript/)
258
- - [wow-react reference](https://wow.ahoo.me/reference/typescript/wow-react/)
262
+ - [TypeScript guide](https://wow.ahoo.me/typescript/)
259
263
  - [Interactive query hook stories](https://wow.ahoo.me/storybook/?path=/docs/react-hooks-wow-queries--docs)
260
264
 
261
265
  [中文](./README.zh-CN.md) · [License](https://github.com/Ahoo-Wang/Wow/blob/main/LICENSE)
package/README.zh-CN.md CHANGED
@@ -22,7 +22,7 @@ pnpm add react react-dom @ahoo-wang/fetcher @ahoo-wang/fetcher-eventstream \
22
22
 
23
23
  `@ahoo-wang/fetcher-eventstream` 是 `@ahoo-wang/wow-client` 的 peer,不是本包的。
24
24
 
25
- 版本号跟随 Wow,次版本可能带有破坏性改动:用 `save-prefix=~` 或 `--save-exact` 让 Wow 包停在同一个次版本上,见[版本范围](https://wow.ahoo.me/zh/guide/typescript/compatibility#版本范围)。
25
+ 版本号跟随 Wow,次版本可能带有破坏性改动:用 `save-prefix=~` 或 `--save-exact` 让 Wow 包停在同一个次版本上,见[版本范围](https://wow.ahoo.me/zh/typescript/compatibility#版本范围)。
26
26
 
27
27
  这些 hook 自带请求状态机:不需要 `@ahoo-wang/fetcher-react`,也不需要
28
28
  `@ahoo-wang/fetcher-wow`。
@@ -32,27 +32,23 @@ pnpm add react react-dom @ahoo-wang/fetcher @ahoo-wang/fetcher-eventstream \
32
32
 
33
33
  ## 配合查询客户端
34
34
 
35
- `use*Query` 这组 hook 接收一个 `execute` 函数。查询客户端的方法——
36
- `@ahoo-wang/wow-client` 的 `SnapshotQueryClient`,或生成的 `…QueryClientFactory`
37
- 创建的客户端——签名恰好是 `execute` 需要的 `(query, attributes, abort)`,于是 URL、
38
- 请求头和响应处理都由客户端负责,不用手写。这些客户端的方法已绑定到实例上,所以
39
- `execute: client.pagedState` 可以直接写;自己对象上的方法要 `.bind(对象)` 或包一层
40
- 箭头函数:
35
+ `use*Query` 这组 hook 接收一个 `execute` 函数:参数是查询与本次运行的请求选项(含 `signal`)。
36
+ `@ahoo-wang/wow-client` 的查询客户端——生成的 `…SnapshotQueryClient` 或 `QueryModelClient`——
37
+ 最后两个参数恰好就是它们,于是路由、请求头和响应处理都由客户端负责,不用手写:
41
38
 
42
39
  ```tsx
43
- import {
44
- filter,
45
- pagedQuery,
46
- type SnapshotQueryClient,
40
+ import type {
41
+ SnapshotQueryClient,
42
+ SnapshotRecord,
47
43
  } from '@ahoo-wang/wow-client';
44
+ import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';
48
45
  import { usePagedQuery } from '@ahoo-wang/wow-react';
49
46
 
50
47
  interface OrderState {
51
- id: string;
52
48
  status: string;
53
49
  }
54
- // 查询可用的字段;生成的客户端会导出这个类型。
55
- type OrderFields = 'aggregateId' | 'state.status';
50
+ // 查询可用的状态字段;生成的客户端会导出这个类型。
51
+ type OrderFields = 'state.status';
56
52
 
57
53
  export function PaidOrders({
58
54
  client,
@@ -61,12 +57,15 @@ export function PaidOrders({
61
57
  client: SnapshotQueryClient<OrderState, OrderFields>;
62
58
  page: number;
63
59
  }) {
64
- const { result, loading, error } = usePagedQuery<OrderState, OrderFields>({
60
+ const { result, loading, error } = usePagedQuery<
61
+ SnapshotRecord<OrderState>,
62
+ OrderFields
63
+ >({
65
64
  query: pagedQuery({
66
65
  filter: filter.eq('state.status', 'PAID'),
67
66
  pagination: { index: page, size: 20 },
68
67
  }),
69
- execute: client.pagedState,
68
+ execute: (query, options) => client.paged(query, options),
70
69
  });
71
70
 
72
71
  if (error) return <p role="alert">订单加载失败</p>;
@@ -74,7 +73,7 @@ export function PaidOrders({
74
73
  return (
75
74
  <ul>
76
75
  {result.list.map(order => (
77
- <li key={order.id}>{order.status}</li>
76
+ <li key={order.aggregateId}>{order.state.status}</li>
78
77
  ))}
79
78
  </ul>
80
79
  );
@@ -83,34 +82,36 @@ export function PaidOrders({
83
82
 
84
83
  像上面这样把客户端的字段类型作为第二个类型参数传入:生成的客户端字段比 `string` 窄,
85
84
  而一旦写出第一个类型参数,TypeScript 就不会再从 `execute` 推断它。
86
- 记得把 `abortController` 传下去:这样新的查询、`abort()`、`reset()` 和组件卸载都会取消请求。
87
- 快照查询过滤的是快照文档,聚合状态在它的 `state` 字段下,所以状态字段写作
88
- `state.status`,而不是 `status`。
85
+ 记得把选项传下去:这样新的查询、`abort()`、`reset()` 和组件卸载都会取消请求。方法要像上面那样
86
+ 包一层箭头函数再交出去:单独交出的方法会丢掉 `this`。
87
+ 快照查询过滤的是快照记录,聚合状态在它的 `state` 字段下,所以状态字段写作
88
+ `state.status`,而不是 `status`。`requestOptions` 为每次运行加上作用域、空间或更多请求头。
89
89
 
90
- 聚合查询暂时没有 Hook,通用的 `useQuery` 与聚合 Hook 计划在 9.3 提供。在此之前,在
91
- effect 里调用 `client.aggregate`,并在清理函数里中止它,写法见
92
- [参考页](https://wow.ahoo.me/zh/reference/typescript/wow-react/#聚合查询)。
90
+ 聚合查询暂时没有 Hook。在 effect 里用 `AbortController` 调用
91
+ `client.aggregate(query, { signal })`,并在清理函数里中止它。
93
92
 
94
93
  游标查询也还没有 Hook。用 `useSingleQuery` 运行它,把一页当作结果:类型参数传
95
- `CursorPage<R>` 与 `CursorQuery<Fields>`,`execute` 传 `client.cursorState`(或
96
- `client.cursor`);`nextCursor` 不为 `null` 时,用
97
- `setQuery({ ...query, cursor: result.nextCursor })` 翻到下一页。
94
+ `CursorPage<R>` 与 `CursorQuery<Fields>`,`execute` 传 `client.cursor`;`nextCursor`
95
+ 不为 `null` 时,用 `setQuery({ ...query, cursor: result.nextCursor })` 翻到下一页。
98
96
 
99
97
  ## 配合端点 URL
100
98
 
101
- `useFetcher*Query` 这组 hook 则通过 Fetcher 把查询 POST 到一个 URL:
99
+ `useFetcher*Query` 这组 hook 则通过 Fetcher 把查询 POST 到一个查询路由:
102
100
 
103
101
  ```tsx
104
102
  import { Fetcher } from '@ahoo-wang/fetcher';
105
- import { filter, pagedQuery } from '@ahoo-wang/wow-client';
103
+ import type { SnapshotRecord } from '@ahoo-wang/wow-client';
104
+ import { filter, pagedQuery } from '@ahoo-wang/wow-client/dsl';
106
105
  import { useFetcherPagedQuery } from '@ahoo-wang/wow-react';
107
106
 
108
- const fetcher = new Fetcher({ baseURL: 'https://api.example.com/' });
107
+ const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
109
108
 
110
109
  export function PaidOrders() {
111
- const { result, loading, error } = useFetcherPagedQuery<OrderState>({
110
+ const { result, loading, error } = useFetcherPagedQuery<
111
+ SnapshotRecord<OrderState>
112
+ >({
112
113
  fetcher,
113
- url: 'order/snapshot/paged/state',
114
+ url: '/shop/order/snapshot/query',
114
115
  initialQuery: pagedQuery({
115
116
  filter: filter.eq('state.status', 'PAID'),
116
117
  pagination: { index: 1, size: 20 },
@@ -121,8 +122,8 @@ export function PaidOrders() {
121
122
  ```
122
123
 
123
124
  `fetcher` 可以是 Fetcher 实例,也可以是已注册 Fetcher 的名字;省略时用默认 Fetcher。
124
- 一个聚合的快照路由是 `{aggregate}/snapshot/{single|list|paged}[/state]` 与
125
- `{aggregate}/snapshot/count`;聚合有上下文别名、owner 或租户路径时,路由前面还要加上它们。
125
+ 一个聚合的快照查询路由是 `/{context}/{aggregate}/snapshot/query`,事件是
126
+ `/{context}/{aggregate}/events/query`;hook 在查询的 `kind` 里写明操作(`single`、`list`、`paged`、`count`)。
126
127
 
127
128
  一次请求由 `url` 与 Fetcher 决定:有名字的 Fetcher 按名字区分,无名的按 `baseURL` 区分。
128
129
  两个 `baseURL` 相同的无名 Fetcher 即使拦截器不同(例如按租户各建一个),也被视为同一个端点,
@@ -131,30 +132,31 @@ export function PaidOrders() {
131
132
  ## 流式读取列表
132
133
 
133
134
  `useListStreamQuery` 与 `useFetcherListStreamQuery` 以服务端推送事件(SSE)读取列表,
134
- 行一到就保存下来。`listQuery()` 只在给出 `limit` 时才发送它:Wow 9.1.5 及以后此时用
135
- 默认列表大小,Wow 8.11~9.1.3 则以 HTTP 400 拒绝,对这些服务端请传 `limit`:
135
+ 行一到就保存下来。服务端中途切断的流会从断点续传,与 wow-client 的 `listStream` 一致。
136
136
 
137
137
  ```tsx
138
- import { filter, listQuery } from '@ahoo-wang/wow-client';
138
+ import type { SnapshotRecord } from '@ahoo-wang/wow-client';
139
+ import { filter, listQuery } from '@ahoo-wang/wow-client/dsl';
139
140
  import { useFetcherListStreamQuery } from '@ahoo-wang/wow-react';
140
141
 
141
142
  export function PaidOrderFeed() {
142
- const { items, done, loading, error, abort } =
143
- useFetcherListStreamQuery<OrderState>({
144
- fetcher,
145
- url: 'order/snapshot/list/state',
146
- initialQuery: listQuery({
147
- filter: filter.eq('state.status', 'PAID'),
148
- limit: 100,
149
- }),
150
- });
143
+ const { items, done, loading, error, abort } = useFetcherListStreamQuery<
144
+ SnapshotRecord<OrderState>
145
+ >({
146
+ fetcher,
147
+ url: '/shop/order/snapshot/query',
148
+ initialQuery: listQuery({
149
+ filter: filter.eq('state.status', 'PAID'),
150
+ limit: 100,
151
+ }),
152
+ });
151
153
 
152
154
  if (error) return <p role="alert">{error.message}</p>;
153
155
  return (
154
156
  <>
155
157
  <ul>
156
158
  {items.map(order => (
157
- <li key={order.id}>{order.id}</li>
159
+ <li key={order.aggregateId}>{order.state.status}</li>
158
160
  ))}
159
161
  </ul>
160
162
  {loading && <button onClick={abort}>停止</button>}
@@ -164,19 +166,19 @@ export function PaidOrderFeed() {
164
166
  }
165
167
  ```
166
168
 
167
- | 字段 | 含义 |
168
- | --------- | ----------------------------------------------------------------------------------------------- |
169
- | `items` | 当前查询到目前为止收到的行,按到达顺序。新查询从空列表开始;`reset()` 清空它。 |
170
- | `done` | 流正常结束,`items` 已包含全部行。等同于 `status === 'success'`。 |
171
- | `loading` | 从发出请求直到流结束、出错或被中止。 |
172
- | `error` | 请求失败时是 `FetcherError`;服务端在流中途发来错误事件时是带服务端 `errorCode` 的 `WowError`。 |
173
- | `abort()` | 停止读取流并保留已收到的行。`reset()` 停止并清空 `items`。`execute()` 重新执行当前查询。 |
169
+ | 字段 | 含义 |
170
+ | --------- | ---------------------------------------------------------------------------------------- |
171
+ | `items` | 当前查询到目前为止收到的行,按到达顺序。新查询从空列表开始;`reset()` 清空它。 |
172
+ | `done` | 流正常结束,`items` 已包含全部行。等同于 `status === 'success'`。 |
173
+ | `loading` | 从发出请求直到流结束、出错或被中止。 |
174
+ | `error` | 请求失败、或服务端在流中途发来错误事件时的 `WowProblemError`。 |
175
+ | `abort()` | 停止读取流并保留已收到的行。`reset()` 停止并清空 `items`。`execute()` 重新执行当前查询。 |
174
176
 
175
177
  流由 hook 自己持有:它负责读取,无论到达多少行,最多约每帧(16 毫秒)渲染一次,并在新查询开始、
176
178
  调用 `abort()` 或 `reset()`、组件卸载时取消流。组件不接触 reader,所以在 StrictMode 下
177
179
  也是安全的。`useFetcherListStreamQuery` 会发送 `Accept: text/event-stream`——Wow
178
- 服务端要看到这个请求头才会以流的形式响应;用 `useListStreamQuery` 时,把客户端的
179
- `listStream` 或 `listStateStream` 作为 `execute` 传入。
180
+ 服务要看到这个请求头才会以流的形式响应;用 `useListStreamQuery` 时,把客户端的
181
+ `listStream` 作为 `execute` 传入。
180
182
 
181
183
  ## 状态与错误
182
184
 
@@ -198,39 +200,39 @@ export function PaidOrderFeed() {
198
200
  `QueryStatus` 与 `QueryExecutor`。`status` 是普通的字符串联合类型
199
201
  `'idle' | 'loading' | 'success' | 'error'`,组件 props 或测试里可以直接写字面量。
200
202
 
201
- `error` 的类型默认是 `Error`,需要更窄时传入类型参数 `E`:请求失败时是
202
- `FetcherError`,流中的错误事件是 `WowError`,自定义的 `execute` 则是它抛出的任何错误。
203
- `@ahoo-wang/wow-client` 的 `toWowError` 能从失败的请求中读出服务端的 `ErrorInfo`:
203
+ `error` 的类型默认是 `Error`,需要更窄时传入类型参数 `E`:请求失败和流中的错误事件都是
204
+ wow-client 的 `WowProblemError`,自定义的 `execute` 则是它抛出的任何错误。problem 带着服务的
205
+ `code` 与 `status`:
204
206
 
205
207
  ```ts
206
- import { ErrorCodes, toWowError } from '@ahoo-wang/wow-client';
208
+ import { FrameworkErrorCodes, WowProblemError } from '@ahoo-wang/wow-client';
207
209
 
208
- const wowError = await toWowError(error);
209
- if (wowError?.errorCode === ErrorCodes.NOT_FOUND) {
210
+ declare const error: unknown;
211
+ if (
212
+ error instanceof WowProblemError &&
213
+ error.code === FrameworkErrorCodes.AGGREGATE_NOT_FOUND
214
+ ) {
210
215
  // …
211
216
  }
212
217
  ```
213
218
 
214
219
  ## Hook 一览
215
220
 
216
- | Hook | 查询 | 结果 |
217
- | ------------------------------------------------- | --------------------------- | ------------------------------- |
218
- | `useSingleQuery`、`useFetcherSingleQuery` | `singleQuery(…)` | `result`:一条 |
219
- | `useListQuery`、`useFetcherListQuery` | `listQuery(…)` | `result`:若干行 |
220
- | `usePagedQuery`、`useFetcherPagedQuery` | `pagedQuery(…)` | `result`:`{ total, list }` |
221
- | `useCountQuery`、`useFetcherCountQuery` | 一个 `filter.*` 表达式 | `result`:记录数 |
222
- | `useListStreamQuery`、`useFetcherListStreamQuery` | `listQuery(…)`,以 SSE 事件 | `items` 陆续到达,结束后 `done` |
221
+ | Hook | 查询 | 结果 |
222
+ | ------------------------------------------------- | --------------------------- | ---------------------------------- |
223
+ | `useSingleQuery`、`useFetcherSingleQuery` | `singleQuery(…)` | `result`:一条 |
224
+ | `useListQuery`、`useFetcherListQuery` | `listQuery(…)` | `result`:若干行 |
225
+ | `usePagedQuery`、`useFetcherPagedQuery` | `pagedQuery(…)` | `result`:`{ total, exact, list }` |
226
+ | `useCountQuery`、`useFetcherCountQuery` | `{ filter, limit? }` | `result`:`{ count, exact }` |
227
+ | `useListStreamQuery`、`useFetcherListStreamQuery` | `listQuery(…)`,以 SSE 事件 | `items` 陆续到达,结束后 `done` |
223
228
 
224
- 查询类型默认使用 `@ahoo-wang/wow-client` 的 `filter` API。每个 hook 也接受
225
- `@ahoo-wang/wow-client/legacy` 中已弃用的 Condition 查询(Wow 8.10 服务端需要);
226
- 这个重载将在 v10 移除。
229
+ 查询用 `@ahoo-wang/wow-client/dsl` 的 DSL 构造。
227
230
 
228
231
  在 Wow 9 中从 `@ahoo-wang/fetcher-react`(其中的 Wow hook)迁移而来;版本号跟随 Wow。
229
232
 
230
233
  ## 文档
231
234
 
232
- - [TypeScript 指南](https://wow.ahoo.me/zh/guide/typescript/)
233
- - [wow-react 参考](https://wow.ahoo.me/zh/reference/typescript/wow-react/)
235
+ - [TypeScript 指南](https://wow.ahoo.me/zh/typescript/)
234
236
  - [交互式查询 hook Story](https://wow.ahoo.me/storybook/?path=/docs/react-hooks-wow-queries--docs)
235
237
 
236
238
  [English](./README.md) · [许可证](https://github.com/Ahoo-Wang/Wow/blob/main/LICENSE)
@@ -1,5 +1,4 @@
1
- import { FilterExpression } from '@ahoo-wang/wow-client';
2
- import { Condition } from '@ahoo-wang/wow-client/legacy';
1
+ import { CountQuery, CountResult } from '@ahoo-wang/wow-client';
3
2
  import { QueryHookOptions, QueryHookReturn } from '../types.js';
4
3
  /**
5
4
  * Options of {@link useCountQuery}: a filter and an `execute` that resolves to
@@ -9,7 +8,7 @@ import { QueryHookOptions, QueryHookReturn } from '../types.js';
9
8
  * @template E - The error type, `Error` by default
10
9
  * @template Q - The filter type: `FilterExpression` by default
11
10
  */
12
- export interface UseCountQueryOptions<FIELDS extends string = string, E = Error, Q extends Condition<FIELDS> | FilterExpression<FIELDS> = FilterExpression<FIELDS>> extends QueryHookOptions<Q, number, E> {
11
+ export interface UseCountQueryOptions<FIELDS extends string = string, E = Error, Q extends CountQuery<FIELDS> = CountQuery<FIELDS>> extends QueryHookOptions<Q, CountResult, E> {
13
12
  }
14
13
  /**
15
14
  * What {@link useCountQuery} returns: the count as `result`.
@@ -18,14 +17,14 @@ export interface UseCountQueryOptions<FIELDS extends string = string, E = Error,
18
17
  * @template E - The error type, `Error` by default
19
18
  * @template Q - The filter type: `FilterExpression` by default
20
19
  */
21
- export interface UseCountQueryReturn<FIELDS extends string = string, E = Error, Q extends Condition<FIELDS> | FilterExpression<FIELDS> = FilterExpression<FIELDS>> extends QueryHookReturn<Q, number, E> {
20
+ export interface UseCountQueryReturn<FIELDS extends string = string, E = Error, Q extends CountQuery<FIELDS> = CountQuery<FIELDS>> extends QueryHookReturn<Q, CountResult, E> {
22
21
  }
23
22
  /**
24
23
  * Counts what a filter matches through your own `execute` function and keeps
25
24
  * the count as state: typically a query client's `count`.
26
25
  *
27
- * `execute` receives the filter, the `attributes` option and an
28
- * `AbortController`; hand the controller on so that a newer query, `abort()`
26
+ * `execute` receives the filter and the request options of the run, its
27
+ * `signal` included; hand them on so that a newer query, `abort()`
29
28
  * or an unmount cancels the request. The count runs on mount and whenever
30
29
  * `query` or `setQuery()` changes the filter; set `autoExecute: false` to run
31
30
  * it only through `execute()`.
@@ -42,20 +41,24 @@ export interface UseCountQueryReturn<FIELDS extends string = string, E = Error,
42
41
  *
43
42
  * @example
44
43
  * ```tsx
45
- * import { filter, type SnapshotQueryClient } from '@ahoo-wang/wow-client';
44
+ * import type { SnapshotQueryClient } from '@ahoo-wang/wow-client';
45
+ * import { filter } from '@ahoo-wang/wow-client/dsl';
46
46
  * import { useCountQuery } from '@ahoo-wang/wow-react';
47
47
  *
48
48
  * function PaidCount({ client }: { client: SnapshotQueryClient<OrderState, OrderFields> }) {
49
49
  * const { result, error } = useCountQuery<OrderFields>({
50
- * initialQuery: filter.eq('state.status', 'PAID'),
51
- * execute: (query, attributes, abortController) =>
52
- * client.count(query, attributes, abortController),
50
+ * initialQuery: { filter: filter.eq('state.status', 'PAID') },
51
+ * execute: (query, options) =>
52
+ * client.count(query, options),
53
53
  * });
54
54
  * if (error) return <p role="alert">{error.message}</p>;
55
- * return <p>{result ?? '…'} paid orders</p>;
55
+ * return <p>{result?.count ?? '…'} paid orders</p>;
56
56
  * }
57
57
  * ```
58
58
  */
59
- export declare function useCountQuery<FIELDS extends string = string, E = Error>(options: UseCountQueryOptions<FIELDS, E, FilterExpression<FIELDS>>): UseCountQueryReturn<FIELDS, E, FilterExpression<FIELDS>>;
60
- export declare function useCountQuery<FIELDS extends string = string, E = Error>(options: UseCountQueryOptions<FIELDS, E, Condition<FIELDS>>): UseCountQueryReturn<FIELDS, E, Condition<FIELDS>>;
61
- export declare function useCountQuery<FIELDS extends string = string, E = Error, Q extends Condition<FIELDS> | FilterExpression<FIELDS> = FilterExpression<FIELDS>>(options: UseCountQueryOptions<FIELDS, E, Q>): UseCountQueryReturn<FIELDS, E, Q>;
59
+ export declare function useCountQuery<FIELDS extends string = string, E = Error>(options: UseCountQueryOptions<FIELDS, E, CountQuery<FIELDS>>): UseCountQueryReturn<FIELDS, E, CountQuery<FIELDS>>;
60
+ /**
61
+ * {@link useCountQuery} typed by a query `Q` of your own, a subtype of
62
+ * `CountQuery`.
63
+ */
64
+ export declare function useCountQuery<FIELDS extends string = string, E = Error, Q extends CountQuery<FIELDS> = CountQuery<FIELDS>>(options: UseCountQueryOptions<FIELDS, E, Q>): UseCountQueryReturn<FIELDS, E, Q>;