@terreno/syncdb 57.9.0 → 57.11.0
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/dist/client.d.ts +20 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +53 -1
- package/dist/client.js.map +1 -1
- package/dist/codegen/emitSdk.d.ts.map +1 -1
- package/dist/codegen/emitSdk.js +2 -0
- package/dist/codegen/emitSdk.js.map +1 -1
- package/dist/codegen/generate.test.js +2 -0
- package/dist/codegen/generate.test.js.map +1 -1
- package/dist/codegen/hookNames.d.ts +2 -1
- package/dist/codegen/hookNames.d.ts.map +1 -1
- package/dist/codegen/hookNames.js +2 -1
- package/dist/codegen/hookNames.js.map +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/query/localQuery.d.ts +22 -0
- package/dist/query/localQuery.d.ts.map +1 -0
- package/dist/query/localQuery.js +38 -0
- package/dist/query/localQuery.js.map +1 -0
- package/dist/query/queryWindows.d.ts +128 -0
- package/dist/query/queryWindows.d.ts.map +1 -0
- package/dist/query/queryWindows.edge.test.d.ts +2 -0
- package/dist/query/queryWindows.edge.test.d.ts.map +1 -0
- package/dist/query/queryWindows.edge.test.js +196 -0
- package/dist/query/queryWindows.edge.test.js.map +1 -0
- package/dist/query/queryWindows.js +621 -0
- package/dist/query/queryWindows.js.map +1 -0
- package/dist/query/queryWindows.test.d.ts +2 -0
- package/dist/query/queryWindows.test.d.ts.map +1 -0
- package/dist/query/queryWindows.test.js +565 -0
- package/dist/query/queryWindows.test.js.map +1 -0
- package/dist/query/rangePlan.d.ts +23 -0
- package/dist/query/rangePlan.d.ts.map +1 -0
- package/dist/query/rangePlan.js +20 -0
- package/dist/query/rangePlan.js.map +1 -0
- package/dist/query/sort.d.ts +13 -0
- package/dist/query/sort.d.ts.map +1 -0
- package/dist/query/sort.js +84 -0
- package/dist/query/sort.js.map +1 -0
- package/dist/query/where.d.ts +41 -0
- package/dist/query/where.d.ts.map +1 -0
- package/dist/query/where.js +243 -0
- package/dist/query/where.js.map +1 -0
- package/dist/query/where.test.d.ts +2 -0
- package/dist/query/where.test.d.ts.map +1 -0
- package/dist/query/where.test.js +130 -0
- package/dist/query/where.test.js.map +1 -0
- package/dist/react/collectionHooks.d.ts +6 -1
- package/dist/react/collectionHooks.d.ts.map +1 -1
- package/dist/react/collectionHooks.js +3 -1
- package/dist/react/collectionHooks.js.map +1 -1
- package/dist/react/hooks.d.ts +66 -2
- package/dist/react/hooks.d.ts.map +1 -1
- package/dist/react/hooks.js +91 -24
- package/dist/react/hooks.js.map +1 -1
- package/dist/react/windowHooks.test.d.ts +2 -0
- package/dist/react/windowHooks.test.d.ts.map +1 -0
- package/dist/react/windowHooks.test.js +132 -0
- package/dist/react/windowHooks.test.js.map +1 -0
- package/dist/storage/schema.d.ts.map +1 -1
- package/dist/storage/schema.js +13 -1
- package/dist/storage/schema.js.map +1 -1
- package/dist/storage/types.d.ts +5 -0
- package/dist/storage/types.d.ts.map +1 -1
- package/dist/storage/types.js +5 -0
- package/dist/storage/types.js.map +1 -1
- package/dist/sync/httpChannel.d.ts +40 -1
- package/dist/sync/httpChannel.d.ts.map +1 -1
- package/dist/sync/httpChannel.js +89 -0
- package/dist/sync/httpChannel.js.map +1 -1
- package/dist/sync/httpChannel.test.js +45 -1
- package/dist/sync/httpChannel.test.js.map +1 -1
- package/dist/types.d.ts +10 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +70 -1
- package/src/codegen/emitSdk.ts +2 -0
- package/src/codegen/generate.test.ts +2 -0
- package/src/codegen/hookNames.ts +3 -1
- package/src/index.ts +18 -0
- package/src/query/localQuery.ts +60 -0
- package/src/query/queryWindows.edge.test.ts +250 -0
- package/src/query/queryWindows.test.ts +665 -0
- package/src/query/queryWindows.ts +848 -0
- package/src/query/rangePlan.ts +39 -0
- package/src/query/sort.ts +101 -0
- package/src/query/where.test.ts +155 -0
- package/src/query/where.ts +290 -0
- package/src/react/collectionHooks.ts +16 -2
- package/src/react/hooks.ts +184 -26
- package/src/react/windowHooks.test.tsx +172 -0
- package/src/storage/schema.ts +13 -0
- package/src/storage/types.ts +6 -0
- package/src/sync/httpChannel.test.ts +65 -1
- package/src/sync/httpChannel.ts +142 -0
- package/src/types.ts +11 -0
package/src/react/hooks.ts
CHANGED
|
@@ -10,11 +10,20 @@
|
|
|
10
10
|
* (and RNW) compatible.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import {useCallback, useRef, useSyncExternalStore} from "react";
|
|
13
|
+
import {useCallback, useEffect, useMemo, useRef, useSyncExternalStore} from "react";
|
|
14
14
|
|
|
15
15
|
import type {SyncDebugEvent, SyncDebugLog, SyncDebugStats} from "../debug/debugLog";
|
|
16
16
|
import {listConflicts} from "../mutations/conflicts";
|
|
17
|
-
import {
|
|
17
|
+
import {applyLocalQuery, type QuerySort} from "../query/localQuery";
|
|
18
|
+
import {
|
|
19
|
+
type QueryWindowState,
|
|
20
|
+
selectWindowView,
|
|
21
|
+
type WindowQuery,
|
|
22
|
+
windowKeyFor,
|
|
23
|
+
} from "../query/queryWindows";
|
|
24
|
+
import type {SortSpec} from "../query/sort";
|
|
25
|
+
import type {WhereFilter} from "../query/where";
|
|
26
|
+
import {CONFLICTS_TABLE, CURSORS_TABLE, OUTBOX_TABLE, QUERY_WINDOWS_TABLE} from "../storage/types";
|
|
18
27
|
import type {ConflictResolutionStrategy, SyncConflict, SyncStatus} from "../types";
|
|
19
28
|
import {useSyncDbClient} from "./provider";
|
|
20
29
|
|
|
@@ -147,14 +156,44 @@ export const useEntity = <TData = Record<string, unknown>>(
|
|
|
147
156
|
};
|
|
148
157
|
|
|
149
158
|
export interface UseQueryOptions<TData> {
|
|
159
|
+
/**
|
|
160
|
+
* Mongo-style filter over decoded data (`{status: "open", created: {$gte: iso}}`).
|
|
161
|
+
* Same syntax as `useWindowQuery` and `modelRouter` list params. Compared by
|
|
162
|
+
* value, so inline objects are fine.
|
|
163
|
+
*/
|
|
164
|
+
where?: WhereFilter;
|
|
150
165
|
/** Keep only entities whose decoded data passes the predicate (runs in JS). */
|
|
151
166
|
filter?: (data: TData) => boolean;
|
|
152
|
-
/**
|
|
153
|
-
sort?:
|
|
167
|
+
/** Comparator, or a sort spec such as `"-created"` / `{created: "descending"}`. */
|
|
168
|
+
sort?: QuerySort<TData>;
|
|
169
|
+
/** Keep only the first N results after filter and sort. */
|
|
170
|
+
limit?: number;
|
|
154
171
|
/** Include soft-deleted (tombstoned) entities; excluded by default. */
|
|
155
172
|
includeDeleted?: boolean;
|
|
156
173
|
}
|
|
157
174
|
|
|
175
|
+
/**
|
|
176
|
+
* Value-stable copies of the serializable query options, so an inline
|
|
177
|
+
* `where: {...}` or `sort: "-created"` does not invalidate the snapshot cache on
|
|
178
|
+
* every render. Function options keep reference identity.
|
|
179
|
+
*/
|
|
180
|
+
const useStableQueryOptions = <TData>(
|
|
181
|
+
options: UseQueryOptions<TData> | undefined
|
|
182
|
+
): UseQueryOptions<TData> => {
|
|
183
|
+
const {filter, includeDeleted, limit, sort, where} = options ?? {};
|
|
184
|
+
const whereKey = where === undefined ? "" : JSON.stringify(where);
|
|
185
|
+
const sortKey = sort === undefined || typeof sort === "function" ? "" : JSON.stringify(sort);
|
|
186
|
+
const stableWhere = useMemo(() => where, [whereKey]);
|
|
187
|
+
const stableSortSpec = useMemo(
|
|
188
|
+
() => sort,
|
|
189
|
+
[sortKey, typeof sort === "function" ? sort : undefined]
|
|
190
|
+
);
|
|
191
|
+
return useMemo(
|
|
192
|
+
() => ({filter, includeDeleted, limit, sort: stableSortSpec, where: stableWhere}),
|
|
193
|
+
[filter, includeDeleted, limit, stableSortSpec, stableWhere]
|
|
194
|
+
);
|
|
195
|
+
};
|
|
196
|
+
|
|
158
197
|
/**
|
|
159
198
|
* Subscribe to a collection; returns the entities' decoded data and re-renders
|
|
160
199
|
* on any table change. Tombstones are excluded unless `includeDeleted` is set;
|
|
@@ -172,7 +211,7 @@ export const useQuery = <TData = Record<string, unknown>>(
|
|
|
172
211
|
options?: UseQueryOptions<TData>
|
|
173
212
|
): TData[] => {
|
|
174
213
|
const client = useSyncDbClient();
|
|
175
|
-
const {filter, includeDeleted, sort} = options
|
|
214
|
+
const {filter, includeDeleted, limit, sort, where} = useStableQueryOptions(options);
|
|
176
215
|
|
|
177
216
|
const subscribe = useCallback(
|
|
178
217
|
(onChange: () => void): (() => void) => {
|
|
@@ -188,17 +227,10 @@ export const useQuery = <TData = Record<string, unknown>>(
|
|
|
188
227
|
const entities = client.store.listEntities<TData>({collection, includeDeleted});
|
|
189
228
|
// E4: a corrupt/legacy row decodes to `data: null` (store.ts's decodeData
|
|
190
229
|
// swallows JSON.parse failures and returns null rather than throwing) —
|
|
191
|
-
//
|
|
192
|
-
// every row's data matches TData (e.g. destructuring a field off it).
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
results = results.filter(filter);
|
|
196
|
-
}
|
|
197
|
-
if (sort) {
|
|
198
|
-
results = [...results].sort(sort);
|
|
199
|
-
}
|
|
200
|
-
return results;
|
|
201
|
-
}, [client, collection, filter, includeDeleted, sort]);
|
|
230
|
+
// applyLocalQuery skips it rather than letting it crash list consumers that
|
|
231
|
+
// assume every row's data matches TData (e.g. destructuring a field off it).
|
|
232
|
+
return applyLocalQuery(entities, {filter, limit, sort, where}).map((entity) => entity.data);
|
|
233
|
+
}, [client, collection, filter, includeDeleted, limit, sort, where]);
|
|
202
234
|
|
|
203
235
|
return useCachedExternalStore(subscribe, select);
|
|
204
236
|
};
|
|
@@ -223,7 +255,7 @@ export const useEntityIds = <TData = Record<string, unknown>>(
|
|
|
223
255
|
options?: UseQueryOptions<TData>
|
|
224
256
|
): string[] => {
|
|
225
257
|
const client = useSyncDbClient();
|
|
226
|
-
const {filter, includeDeleted, sort} = options
|
|
258
|
+
const {filter, includeDeleted, limit, sort, where} = useStableQueryOptions(options);
|
|
227
259
|
|
|
228
260
|
const subscribe = useCallback(
|
|
229
261
|
(onChange: () => void): (() => void) => {
|
|
@@ -237,19 +269,145 @@ export const useEntityIds = <TData = Record<string, unknown>>(
|
|
|
237
269
|
|
|
238
270
|
const select = useCallback((): string[] => {
|
|
239
271
|
const entities = client.store.listEntities<TData>({collection, includeDeleted});
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
results = results.filter((entity) => filter(entity.data));
|
|
243
|
-
}
|
|
244
|
-
if (sort) {
|
|
245
|
-
results = [...results].sort((a, b) => sort(a.data, b.data));
|
|
246
|
-
}
|
|
247
|
-
return results.map((entity) => entity.id);
|
|
248
|
-
}, [client, collection, filter, includeDeleted, sort]);
|
|
272
|
+
return applyLocalQuery(entities, {filter, limit, sort, where}).map((entity) => entity.id);
|
|
273
|
+
}, [client, collection, filter, includeDeleted, limit, sort, where]);
|
|
249
274
|
|
|
250
275
|
return useCachedExternalStore(subscribe, select, idsEqual);
|
|
251
276
|
};
|
|
252
277
|
|
|
278
|
+
export interface UseWindowQueryOptions {
|
|
279
|
+
/** Mongo-style filter sent as list params (fields must be in the route's `queryFields`). */
|
|
280
|
+
where?: WhereFilter;
|
|
281
|
+
/** Server sort (`"-created"`); also orders the local view. */
|
|
282
|
+
sort?: SortSpec;
|
|
283
|
+
/** Server page size (default 50). */
|
|
284
|
+
pageSize?: number;
|
|
285
|
+
/** Do not retain or fetch the window (e.g. while a required param is missing). */
|
|
286
|
+
skip?: boolean;
|
|
287
|
+
/**
|
|
288
|
+
* Show cached rows that newly match `where` inside the loaded range (live
|
|
289
|
+
* deltas, local creates) without waiting for a refetch. Default true.
|
|
290
|
+
*/
|
|
291
|
+
liveMatch?: boolean;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export interface UseWindowQueryResult<TData> {
|
|
295
|
+
/** This window's rows, decoded, in view order. */
|
|
296
|
+
data: TData[];
|
|
297
|
+
/** Ids matching `data`. */
|
|
298
|
+
ids: string[];
|
|
299
|
+
/** True until the first page lands and no cached membership exists. */
|
|
300
|
+
isLoading: boolean;
|
|
301
|
+
/** True while any request for this window is in flight. */
|
|
302
|
+
isFetching: boolean;
|
|
303
|
+
isError: boolean;
|
|
304
|
+
error?: string;
|
|
305
|
+
/**
|
|
306
|
+
* Server error code of the last failure. `"query-param-not-allowed"` means a
|
|
307
|
+
* `where` field is missing from the route's `queryFields` (also logged with
|
|
308
|
+
* console.error and thrown as `QueryFieldNotAllowedError` from `refetch`).
|
|
309
|
+
*/
|
|
310
|
+
errorCode?: string;
|
|
311
|
+
/** More server pages exist past the loaded range. */
|
|
312
|
+
hasMore: boolean;
|
|
313
|
+
/** Server-reported total, when available. */
|
|
314
|
+
total?: number;
|
|
315
|
+
/** Append the next server page. */
|
|
316
|
+
fetchNextPage: () => Promise<void>;
|
|
317
|
+
/** Refetch every loaded page, replacing membership. */
|
|
318
|
+
refetch: () => Promise<void>;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
interface WindowSnapshot<TData> {
|
|
322
|
+
entities: Array<{id: string; data: TData}>;
|
|
323
|
+
window: QueryWindowState | undefined;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Server-filtered list over a `queryCollections` collection — the syncdb
|
|
328
|
+
* counterpart of an RTK list query (`where`, `sort`, `limit`/`page`).
|
|
329
|
+
*
|
|
330
|
+
* Each distinct query keeps its own membership, while rows are stored once per
|
|
331
|
+
* id in the shared entity table: two screens whose filters overlap share those
|
|
332
|
+
* rows, a delta for one of them is applied once and re-renders both, and each
|
|
333
|
+
* screen still lists only the rows its own query returned (plus rows that
|
|
334
|
+
* newly match it locally, see `liveMatch`). Cached membership renders
|
|
335
|
+
* immediately offline; the window revalidates once per session and on reconnect.
|
|
336
|
+
*/
|
|
337
|
+
export const useWindowQuery = <TData = Record<string, unknown>>(
|
|
338
|
+
collection: string,
|
|
339
|
+
options?: UseWindowQueryOptions
|
|
340
|
+
): UseWindowQueryResult<TData> => {
|
|
341
|
+
const client = useSyncDbClient();
|
|
342
|
+
const {liveMatch = true, pageSize, skip = false, sort, where} = options ?? {};
|
|
343
|
+
const queryKey = windowKeyFor({collection, pageSize, sort, where});
|
|
344
|
+
const query = useMemo((): WindowQuery => ({collection, pageSize, sort, where}), [queryKey]);
|
|
345
|
+
|
|
346
|
+
// Retain the window while mounted so it fetches once per session and refetches on reconnect.
|
|
347
|
+
useEffect(() => {
|
|
348
|
+
if (skip) {
|
|
349
|
+
return undefined;
|
|
350
|
+
}
|
|
351
|
+
return client.queryWindows.retain(query);
|
|
352
|
+
}, [client, query, skip]);
|
|
353
|
+
|
|
354
|
+
const subscribe = useCallback(
|
|
355
|
+
(onChange: () => void): (() => void) => {
|
|
356
|
+
const tableListener = client.store.raw.addTableListener(collection, onChange);
|
|
357
|
+
const windowListener = client.store.raw.addRowListener(
|
|
358
|
+
QUERY_WINDOWS_TABLE,
|
|
359
|
+
queryKey,
|
|
360
|
+
onChange
|
|
361
|
+
);
|
|
362
|
+
const unsubscribeStatus = client.queryWindows.subscribe(onChange);
|
|
363
|
+
return () => {
|
|
364
|
+
client.store.raw.delListener(tableListener);
|
|
365
|
+
client.store.raw.delListener(windowListener);
|
|
366
|
+
unsubscribeStatus();
|
|
367
|
+
};
|
|
368
|
+
},
|
|
369
|
+
[client, collection, queryKey]
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
const select = useCallback((): WindowSnapshot<TData> => {
|
|
373
|
+
const window = client.queryWindows.getWindow(query);
|
|
374
|
+
const entities = selectWindowView<TData>({liveMatch, query, store: client.store, window});
|
|
375
|
+
return {
|
|
376
|
+
entities: entities.map((entity) => ({data: entity.data, id: entity.id})),
|
|
377
|
+
window,
|
|
378
|
+
};
|
|
379
|
+
}, [client, liveMatch, query]);
|
|
380
|
+
|
|
381
|
+
const snapshot = useCachedExternalStore(subscribe, select);
|
|
382
|
+
|
|
383
|
+
const fetchNextPage = useCallback(async (): Promise<void> => {
|
|
384
|
+
await client.queryWindows.fetchWindow({nextPage: true, query});
|
|
385
|
+
}, [client, query]);
|
|
386
|
+
|
|
387
|
+
const refetch = useCallback(async (): Promise<void> => {
|
|
388
|
+
await client.queryWindows.fetchWindow({query});
|
|
389
|
+
}, [client, query]);
|
|
390
|
+
|
|
391
|
+
return useMemo((): UseWindowQueryResult<TData> => {
|
|
392
|
+
const {window} = snapshot;
|
|
393
|
+
const isFetching = window?.status === "loading";
|
|
394
|
+
return {
|
|
395
|
+
data: snapshot.entities.map((entity) => entity.data),
|
|
396
|
+
error: window?.error,
|
|
397
|
+
errorCode: window?.errorCode,
|
|
398
|
+
fetchNextPage,
|
|
399
|
+
hasMore: window?.hasMore ?? false,
|
|
400
|
+
ids: snapshot.entities.map((entity) => entity.id),
|
|
401
|
+
isError: window?.status === "error",
|
|
402
|
+
isFetching,
|
|
403
|
+
isLoading:
|
|
404
|
+
!skip && (window === undefined || (window.pages === 0 && window.status !== "error")),
|
|
405
|
+
refetch,
|
|
406
|
+
total: window?.total,
|
|
407
|
+
};
|
|
408
|
+
}, [fetchNextPage, refetch, skip, snapshot]);
|
|
409
|
+
};
|
|
410
|
+
|
|
253
411
|
export interface UseMutateResult {
|
|
254
412
|
/** Optimistically create an entity; returns the generated ids. */
|
|
255
413
|
create: (args: {data: Record<string, unknown>; id?: string; maxAttempts?: number}) => {
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import {act, renderHook, waitFor} from "@testing-library/react-native";
|
|
3
|
+
import React from "react";
|
|
4
|
+
|
|
5
|
+
import {createSyncDb, type SyncDb} from "../client";
|
|
6
|
+
import {memoryPersisterFactory} from "../persisters/memoryPersister";
|
|
7
|
+
import {compileWhere} from "../query/where";
|
|
8
|
+
import type {HttpChannel} from "../sync/httpChannel";
|
|
9
|
+
import {createFakeTransport, type FakeTransport} from "../testing/fakeTransport";
|
|
10
|
+
import type {AuthProvider} from "../types";
|
|
11
|
+
import {useQuery, useWindowQuery} from "./hooks";
|
|
12
|
+
import {SyncDbProvider} from "./provider";
|
|
13
|
+
|
|
14
|
+
interface Message {
|
|
15
|
+
_id: string;
|
|
16
|
+
_syncSeq: number;
|
|
17
|
+
threadId: string;
|
|
18
|
+
pinned: boolean;
|
|
19
|
+
text: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const ROWS: Message[] = [
|
|
23
|
+
{_id: "m1", _syncSeq: 1, pinned: false, text: "one", threadId: "a"},
|
|
24
|
+
{_id: "m2", _syncSeq: 1, pinned: true, text: "two", threadId: "a"},
|
|
25
|
+
{_id: "m3", _syncSeq: 1, pinned: true, text: "three", threadId: "b"},
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
const auth: AuthProvider = {
|
|
29
|
+
getToken: async () => "token",
|
|
30
|
+
getUserId: async () => "u1",
|
|
31
|
+
onAuthChange: () => () => {},
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
let nameCounter = 0;
|
|
35
|
+
|
|
36
|
+
interface Harness {
|
|
37
|
+
client: SyncDb;
|
|
38
|
+
transport: FakeTransport;
|
|
39
|
+
listCalls: number;
|
|
40
|
+
wrapper: React.FC<{children: React.ReactNode}>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const setup = async (): Promise<Harness> => {
|
|
44
|
+
nameCounter += 1;
|
|
45
|
+
const transport = createFakeTransport();
|
|
46
|
+
const harness = {listCalls: 0} as Harness;
|
|
47
|
+
const channel: HttpChannel = {
|
|
48
|
+
fetchEntities: async () => ({entities: []}),
|
|
49
|
+
fetchKeyMaterial: async () => "",
|
|
50
|
+
fetchList: async ({params}) => {
|
|
51
|
+
harness.listCalls += 1;
|
|
52
|
+
const {limit: _limit, page: _page, sort: _sort, ...where} = params;
|
|
53
|
+
const {match} = compileWhere(where);
|
|
54
|
+
return {data: ROWS.filter((row) => match?.(row)), more: false};
|
|
55
|
+
},
|
|
56
|
+
fetchSnapshotPage: async ({stream}) => ({
|
|
57
|
+
cursor: 0,
|
|
58
|
+
entities: [],
|
|
59
|
+
frontierSeq: 0,
|
|
60
|
+
hasMore: false,
|
|
61
|
+
oldestRetainedSeq: 0,
|
|
62
|
+
stream,
|
|
63
|
+
}),
|
|
64
|
+
fetchStreams: async () => [],
|
|
65
|
+
sendMutation: async () => {
|
|
66
|
+
throw new Error("not expected");
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
const client = createSyncDb({
|
|
70
|
+
authProvider: auth,
|
|
71
|
+
collections: ["messages"],
|
|
72
|
+
httpChannel: channel,
|
|
73
|
+
name: `window-hooks-test-${nameCounter}`,
|
|
74
|
+
persisterFactory: memoryPersisterFactory,
|
|
75
|
+
queryCollections: ["messages"],
|
|
76
|
+
reconcileIntervalMs: 0,
|
|
77
|
+
transport,
|
|
78
|
+
});
|
|
79
|
+
await client.start();
|
|
80
|
+
await client.reconcile();
|
|
81
|
+
harness.client = client;
|
|
82
|
+
harness.transport = transport;
|
|
83
|
+
harness.wrapper = ({children}) => <SyncDbProvider client={client}>{children}</SyncDbProvider>;
|
|
84
|
+
return harness;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
describe("useWindowQuery", () => {
|
|
88
|
+
it("renders two overlapping filtered views from shared rows", async () => {
|
|
89
|
+
const harness = await setup();
|
|
90
|
+
const {client, transport, wrapper} = harness;
|
|
91
|
+
const {result} = renderHook(
|
|
92
|
+
() => ({
|
|
93
|
+
pinned: useWindowQuery<Message>("messages", {where: {pinned: true}}),
|
|
94
|
+
threadA: useWindowQuery<Message>("messages", {where: {threadId: "a"}}),
|
|
95
|
+
}),
|
|
96
|
+
{wrapper}
|
|
97
|
+
);
|
|
98
|
+
expect(result.current.threadA.isLoading).toBe(true);
|
|
99
|
+
|
|
100
|
+
await waitFor(() => {
|
|
101
|
+
expect(result.current.threadA.ids).toEqual(["m1", "m2"]);
|
|
102
|
+
expect(result.current.pinned.ids).toEqual(["m2", "m3"]);
|
|
103
|
+
});
|
|
104
|
+
expect(result.current.threadA.isLoading).toBe(false);
|
|
105
|
+
expect(harness.listCalls).toBe(2);
|
|
106
|
+
|
|
107
|
+
act(() => {
|
|
108
|
+
transport.deliverDelta({
|
|
109
|
+
collection: "messages",
|
|
110
|
+
data: {...ROWS[1], text: "two edited"},
|
|
111
|
+
id: "m2",
|
|
112
|
+
method: "update",
|
|
113
|
+
seq: 2,
|
|
114
|
+
stream: "messages|owner:u1",
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
expect(result.current.threadA.data.find((row) => row._id === "m2")?.text).toBe("two edited");
|
|
118
|
+
expect(result.current.pinned.data.find((row) => row._id === "m2")?.text).toBe("two edited");
|
|
119
|
+
|
|
120
|
+
await act(async () => {
|
|
121
|
+
await client.stop();
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("does not refetch when rerendered with an equal inline query", async () => {
|
|
126
|
+
const harness = await setup();
|
|
127
|
+
const {client, wrapper} = harness;
|
|
128
|
+
const {result, rerender} = renderHook(
|
|
129
|
+
() => useWindowQuery<Message>("messages", {where: {threadId: "a"}}),
|
|
130
|
+
{wrapper}
|
|
131
|
+
);
|
|
132
|
+
await waitFor(() => {
|
|
133
|
+
expect(result.current.ids).toEqual(["m1", "m2"]);
|
|
134
|
+
});
|
|
135
|
+
rerender({});
|
|
136
|
+
rerender({});
|
|
137
|
+
expect(harness.listCalls).toBe(1);
|
|
138
|
+
await act(async () => {
|
|
139
|
+
await client.stop();
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("does nothing while skip is set", async () => {
|
|
144
|
+
const harness = await setup();
|
|
145
|
+
const {client, wrapper} = harness;
|
|
146
|
+
const {result} = renderHook(
|
|
147
|
+
() => useWindowQuery<Message>("messages", {skip: true, where: {threadId: "a"}}),
|
|
148
|
+
{wrapper}
|
|
149
|
+
);
|
|
150
|
+
expect(result.current.isLoading).toBe(false);
|
|
151
|
+
expect(result.current.data).toEqual([]);
|
|
152
|
+
expect(harness.listCalls).toBe(0);
|
|
153
|
+
await act(async () => {
|
|
154
|
+
await client.stop();
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
describe("useQuery where/sort/limit", () => {
|
|
160
|
+
it("filters, sorts, and limits local rows with the shared syntax", async () => {
|
|
161
|
+
const {client, wrapper} = await setup();
|
|
162
|
+
await client.queryWindows.fetchWindow({query: {collection: "messages"}});
|
|
163
|
+
const {result} = renderHook(
|
|
164
|
+
() => useQuery<Message>("messages", {limit: 1, sort: "-text", where: {pinned: true}}),
|
|
165
|
+
{wrapper}
|
|
166
|
+
);
|
|
167
|
+
expect(result.current.map((row) => row._id)).toEqual(["m2"]);
|
|
168
|
+
await act(async () => {
|
|
169
|
+
await client.stop();
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
});
|
package/src/storage/schema.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
KNOWN_STREAMS_TABLE,
|
|
7
7
|
NEEDS_REPAIR_TABLE,
|
|
8
8
|
OUTBOX_TABLE,
|
|
9
|
+
QUERY_WINDOWS_TABLE,
|
|
9
10
|
} from "./types";
|
|
10
11
|
|
|
11
12
|
/**
|
|
@@ -89,6 +90,18 @@ export const buildTablesSchema = ({collections}: {collections: string[]}): Table
|
|
|
89
90
|
status: {type: "string"},
|
|
90
91
|
userId: {type: "string"},
|
|
91
92
|
},
|
|
93
|
+
[QUERY_WINDOWS_TABLE]: {
|
|
94
|
+
collection: {type: "string"},
|
|
95
|
+
/** JSON-encoded {id: seq} of cached rows the last full fetch proved stale for the window. */
|
|
96
|
+
excluded: {type: "string"},
|
|
97
|
+
fetchedAt: {type: "string"},
|
|
98
|
+
hasMore: {type: "boolean"},
|
|
99
|
+
/** JSON-encoded ordered member ids. */
|
|
100
|
+
ids: {type: "string"},
|
|
101
|
+
pages: {type: "number"},
|
|
102
|
+
/** Server total, or -1 when the endpoint did not report one. */
|
|
103
|
+
total: {type: "number"},
|
|
104
|
+
},
|
|
92
105
|
};
|
|
93
106
|
for (const collection of collections) {
|
|
94
107
|
schema[collection] = {...ENTITY_TABLE_SCHEMA};
|
package/src/storage/types.ts
CHANGED
|
@@ -35,6 +35,12 @@ export const KNOWN_STREAMS_TABLE = "_knownStreams";
|
|
|
35
35
|
*/
|
|
36
36
|
export const NEEDS_REPAIR_TABLE = "_needsRepair";
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Server query-window membership (see `query/queryWindows.ts`); rowId = window key.
|
|
40
|
+
* Holds ordered member ids only — the rows themselves live in the shared entity table.
|
|
41
|
+
*/
|
|
42
|
+
export const QUERY_WINDOWS_TABLE = "_queryWindows";
|
|
43
|
+
|
|
38
44
|
/** Prefix marking reserved (non-collection) tables. */
|
|
39
45
|
export const RESERVED_TABLE_PREFIX = "_";
|
|
40
46
|
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import {describe, expect, it} from "bun:test";
|
|
2
2
|
|
|
3
3
|
import type {AuthProvider} from "../types";
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
AuthRequiredError,
|
|
6
|
+
createHttpChannel,
|
|
7
|
+
type FetchLike,
|
|
8
|
+
ListRequestError,
|
|
9
|
+
QueryFieldNotAllowedError,
|
|
10
|
+
} from "./httpChannel";
|
|
5
11
|
|
|
6
12
|
const authProvider: Pick<AuthProvider, "getToken"> = {
|
|
7
13
|
getToken: async () => "token-123",
|
|
@@ -344,4 +350,62 @@ describe("createHttpChannel", () => {
|
|
|
344
350
|
await expect(empty.fetchKeyMaterial()).rejects.toThrow(/missing keyMaterial/);
|
|
345
351
|
});
|
|
346
352
|
});
|
|
353
|
+
|
|
354
|
+
describe("fetchList", () => {
|
|
355
|
+
it("qs-encodes params against the list path", async () => {
|
|
356
|
+
const {fetchImpl, requests} = makeFetch(() => json({data: [], limit: 10, more: false}));
|
|
357
|
+
const channel = createHttpChannel({authProvider, baseUrl: "https://api.test", fetchImpl});
|
|
358
|
+
await channel.fetchList?.({params: {completed: false, limit: 10, page: 1}, path: "/todos"});
|
|
359
|
+
expect(decodeURIComponent(requests[0].input)).toBe(
|
|
360
|
+
"https://api.test/todos?completed=false&limit=10&page=1"
|
|
361
|
+
);
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
it("raises QueryFieldNotAllowedError naming the field and allowed queryFields", async () => {
|
|
365
|
+
const {fetchImpl} = makeFetch(() =>
|
|
366
|
+
json(
|
|
367
|
+
{
|
|
368
|
+
code: "query-param-not-allowed",
|
|
369
|
+
detail: 'title is not allowed as a query param. Add "title" to queryFields…',
|
|
370
|
+
meta: {
|
|
371
|
+
allowedQueryFields: ["completed", "ownerId"],
|
|
372
|
+
model: "Todo",
|
|
373
|
+
queryParam: "title",
|
|
374
|
+
},
|
|
375
|
+
source: {parameter: "title"},
|
|
376
|
+
status: 400,
|
|
377
|
+
title: "Query parameter not allowed",
|
|
378
|
+
},
|
|
379
|
+
400
|
|
380
|
+
)
|
|
381
|
+
);
|
|
382
|
+
const channel = createHttpChannel({authProvider, baseUrl: "https://api.test", fetchImpl});
|
|
383
|
+
const error = await channel
|
|
384
|
+
.fetchList?.({params: {title: "x"}, path: "/todos"})
|
|
385
|
+
.catch((caught: unknown) => caught);
|
|
386
|
+
expect(error).toBeInstanceOf(QueryFieldNotAllowedError);
|
|
387
|
+
const typed = error as QueryFieldNotAllowedError;
|
|
388
|
+
expect(typed.field).toBe("title");
|
|
389
|
+
expect(typed.allowedQueryFields).toEqual(["completed", "ownerId"]);
|
|
390
|
+
expect(typed.model).toBe("Todo");
|
|
391
|
+
expect(typed.code).toBe("query-param-not-allowed");
|
|
392
|
+
expect(typed.message).toContain('Add "title" to queryFields');
|
|
393
|
+
expect(typed.message).toContain("Allowed: completed, ownerId.");
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
it("raises ListRequestError with the server detail for other failures", async () => {
|
|
397
|
+
const {fetchImpl} = makeFetch(() =>
|
|
398
|
+
json({code: "list-error", detail: "boom", status: 500, title: "List error"}, 500)
|
|
399
|
+
);
|
|
400
|
+
const channel = createHttpChannel({authProvider, baseUrl: "https://api.test", fetchImpl});
|
|
401
|
+
const error = await channel
|
|
402
|
+
.fetchList?.({params: {}, path: "/todos"})
|
|
403
|
+
.catch((caught: unknown) => caught);
|
|
404
|
+
expect(error).toBeInstanceOf(ListRequestError);
|
|
405
|
+
expect(error).not.toBeInstanceOf(QueryFieldNotAllowedError);
|
|
406
|
+
expect((error as ListRequestError).message).toBe(
|
|
407
|
+
"List request for /todos failed with status 500: boom"
|
|
408
|
+
);
|
|
409
|
+
});
|
|
410
|
+
});
|
|
347
411
|
});
|