@hyper-fetch/db 0.0.0-stage → 10.2.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/README.md +180 -2
- package/__tests__/e2e/db.e2e.spec.ts +269 -0
- package/__tests__/features/connection/connection.spec.ts +23 -0
- package/__tests__/features/model/live-query.model.spec.ts +320 -0
- package/__tests__/features/operators/operators.spec.ts +113 -0
- package/__tests__/features/runtime/runtime.spec.ts +185 -0
- package/__tests__/features/serializer/serializer.spec.ts +73 -0
- package/__tests__/features/store/store.spec.ts +147 -0
- package/__tests__/features/types/db.types.spec.ts +337 -0
- package/__tests__/integration/audit.spec.ts +639 -0
- package/__tests__/integration/competitors.spec.ts +393 -0
- package/__tests__/integration/convergence.model.spec.ts +162 -0
- package/__tests__/integration/edge-cases.spec.ts +465 -0
- package/__tests__/integration/errors.spec.ts +178 -0
- package/__tests__/integration/infinite.model.spec.ts +142 -0
- package/__tests__/integration/infinite.spec.ts +290 -0
- package/__tests__/integration/inspect.spec.ts +103 -0
- package/__tests__/integration/joins-many.spec.ts +177 -0
- package/__tests__/integration/joins.spec.ts +179 -0
- package/__tests__/integration/key-loaders.spec.ts +196 -0
- package/__tests__/integration/links.spec.ts +105 -0
- package/__tests__/integration/mutations.spec.ts +337 -0
- package/__tests__/integration/normalize.spec.ts +80 -0
- package/__tests__/integration/offline.spec.ts +479 -0
- package/__tests__/integration/queries.spec.ts +513 -0
- package/__tests__/integration/races.spec.ts +127 -0
- package/__tests__/integration/server-operators.spec.ts +123 -0
- package/__tests__/integration/ssr.spec.ts +111 -0
- package/__tests__/integration/syncs.spec.ts +564 -0
- package/__tests__/integration/transactions.spec.ts +344 -0
- package/__tests__/integration/windows.spec.ts +192 -0
- package/__tests__/tsconfig.json +11 -0
- package/__tests__/type-budget/budget.fixture.ts +2476 -0
- package/__tests__/type-budget/tsconfig.json +4 -0
- package/__tests__/utils/fixtures.ts +225 -0
- package/__tests__/utils/random.ts +19 -0
- package/__tests__/vitest.setup.ts +11 -0
- package/dist/collection/collection.d.ts +111 -0
- package/dist/collection/collection.d.ts.map +1 -0
- package/dist/collection/collection.types.d.ts +316 -0
- package/dist/collection/collection.types.d.ts.map +1 -0
- package/dist/collection/resource.types.d.ts +77 -0
- package/dist/collection/resource.types.d.ts.map +1 -0
- package/dist/db/collection.runtime.d.ts +98 -0
- package/dist/db/collection.runtime.d.ts.map +1 -0
- package/dist/db/db.d.ts +154 -0
- package/dist/db/db.d.ts.map +1 -0
- package/dist/db/db.runtime.d.ts +114 -0
- package/dist/db/db.runtime.d.ts.map +1 -0
- package/dist/db/db.types.d.ts +162 -0
- package/dist/db/db.types.d.ts.map +1 -0
- package/dist/graphql/connection.d.ts +25 -0
- package/dist/graphql/connection.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.mjs +4220 -0
- package/dist/index.mjs.map +1 -0
- package/dist/mutation/mutation.d.ts +136 -0
- package/dist/mutation/mutation.d.ts.map +1 -0
- package/dist/mutation/mutation.errors.d.ts +6 -0
- package/dist/mutation/mutation.errors.d.ts.map +1 -0
- package/dist/mutation/mutation.utils.d.ts +35 -0
- package/dist/mutation/mutation.utils.d.ts.map +1 -0
- package/dist/operators/operators.d.ts +33 -0
- package/dist/operators/operators.d.ts.map +1 -0
- package/dist/operators/operators.types.d.ts +68 -0
- package/dist/operators/operators.types.d.ts.map +1 -0
- package/dist/operators/operators.utils.d.ts +19 -0
- package/dist/operators/operators.utils.d.ts.map +1 -0
- package/dist/persistence/persistence.d.ts +42 -0
- package/dist/persistence/persistence.d.ts.map +1 -0
- package/dist/persistence/serializer.d.ts +23 -0
- package/dist/persistence/serializer.d.ts.map +1 -0
- package/dist/persistence/snapshot.d.ts +29 -0
- package/dist/persistence/snapshot.d.ts.map +1 -0
- package/dist/persistence/tabs.d.ts +53 -0
- package/dist/persistence/tabs.d.ts.map +1 -0
- package/dist/query/infinite-query.d.ts +59 -0
- package/dist/query/infinite-query.d.ts.map +1 -0
- package/dist/query/live-query.d.ts +85 -0
- package/dist/query/live-query.d.ts.map +1 -0
- package/dist/query/planner.d.ts +57 -0
- package/dist/query/planner.d.ts.map +1 -0
- package/dist/query/query.d.ts +155 -0
- package/dist/query/query.d.ts.map +1 -0
- package/dist/query/query.types.d.ts +71 -0
- package/dist/query/query.types.d.ts.map +1 -0
- package/dist/schema/schema.types.d.ts +33 -0
- package/dist/schema/schema.types.d.ts.map +1 -0
- package/dist/store/store.d.ts +76 -0
- package/dist/store/store.d.ts.map +1 -0
- package/dist/store/store.types.d.ts +27 -0
- package/dist/store/store.types.d.ts.map +1 -0
- package/dist/subset/base-subset.d.ts +66 -0
- package/dist/subset/base-subset.d.ts.map +1 -0
- package/dist/subset/key-subset.d.ts +23 -0
- package/dist/subset/key-subset.d.ts.map +1 -0
- package/dist/subset/list-subset.d.ts +63 -0
- package/dist/subset/list-subset.d.ts.map +1 -0
- package/dist/sync/sync.d.ts +42 -0
- package/dist/sync/sync.d.ts.map +1 -0
- package/dist/utils/request.utils.d.ts +11 -0
- package/dist/utils/request.utils.d.ts.map +1 -0
- package/package.json +71 -4
- package/project.json +4 -0
- package/scripts/docs-typescript.mjs +24 -0
- package/scripts/type-budget.mjs +37 -0
- package/src/collection/collection.ts +330 -0
- package/src/collection/collection.types.ts +383 -0
- package/src/collection/resource.types.ts +114 -0
- package/src/db/collection.runtime.ts +572 -0
- package/src/db/db.runtime.ts +537 -0
- package/src/db/db.ts +451 -0
- package/src/db/db.types.ts +157 -0
- package/src/graphql/connection.ts +23 -0
- package/src/index.ts +16 -0
- package/src/mutation/mutation.errors.ts +7 -0
- package/src/mutation/mutation.ts +776 -0
- package/src/mutation/mutation.utils.ts +58 -0
- package/src/operators/operators.ts +90 -0
- package/src/operators/operators.types.ts +67 -0
- package/src/operators/operators.utils.ts +169 -0
- package/src/persistence/persistence.ts +168 -0
- package/src/persistence/serializer.ts +123 -0
- package/src/persistence/snapshot.ts +76 -0
- package/src/persistence/tabs.ts +86 -0
- package/src/query/infinite-query.ts +206 -0
- package/src/query/live-query.ts +552 -0
- package/src/query/planner.ts +199 -0
- package/src/query/query.ts +319 -0
- package/src/query/query.types.ts +90 -0
- package/src/schema/schema.types.ts +29 -0
- package/src/store/store.ts +300 -0
- package/src/store/store.types.ts +17 -0
- package/src/subset/base-subset.ts +169 -0
- package/src/subset/key-subset.ts +44 -0
- package/src/subset/list-subset.ts +328 -0
- package/src/sync/sync.ts +99 -0
- package/src/utils/request.utils.ts +67 -0
- package/tsconfig.json +12 -0
- package/vite.config.ts +71 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { DependencyError, collection, createDb, eq } from "@hyper-fetch/db";
|
|
2
|
+
import type { DbErrorEvent, DbOptions, StandardSchemaV1, TransactionWrite } from "@hyper-fetch/db";
|
|
3
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
4
|
+
|
|
5
|
+
import type { Post } from "../utils/fixtures";
|
|
6
|
+
import {
|
|
7
|
+
PostSchema,
|
|
8
|
+
createApi,
|
|
9
|
+
createHttpClient,
|
|
10
|
+
createMemoryStorage,
|
|
11
|
+
createPost,
|
|
12
|
+
createRequests,
|
|
13
|
+
deferred,
|
|
14
|
+
flush,
|
|
15
|
+
} from "../utils/fixtures";
|
|
16
|
+
|
|
17
|
+
const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
|
|
18
|
+
|
|
19
|
+
const byTeam = { teamId: { eq: (teamId: number) => ({ params: { teamId } }), required: true as const } };
|
|
20
|
+
|
|
21
|
+
const createCollections = () => {
|
|
22
|
+
const client = createHttpClient();
|
|
23
|
+
const requests = createRequests(client);
|
|
24
|
+
const publish = client.createRequest<{
|
|
25
|
+
response: { ok: boolean };
|
|
26
|
+
payload: { mutations: TransactionWrite[]; idempotencyKey: string };
|
|
27
|
+
}>()({ endpoint: "/publish", method: "POST" });
|
|
28
|
+
const post = collection(PostSchema, { key: "id" })
|
|
29
|
+
.load(requests.getTeamFullPosts, { rows: (response) => response.items, where: byTeam })
|
|
30
|
+
.mutate({
|
|
31
|
+
insert: { request: requests.createPostRequest, map: (row) => ({ payload: row }) },
|
|
32
|
+
update: {
|
|
33
|
+
request: requests.updatePostRequest,
|
|
34
|
+
map: (key, changes) => ({ params: { postId: key }, payload: changes }),
|
|
35
|
+
},
|
|
36
|
+
delete: { request: requests.deletePostRequest, map: (key) => ({ params: { postId: key } }), onSuccess: "keep" },
|
|
37
|
+
});
|
|
38
|
+
// A backend that applies writes on its own, so writes add no optimistic layer
|
|
39
|
+
const remote = collection(PostSchema, { key: "id" })
|
|
40
|
+
.load(requests.getPost, { byKey: (id) => ({ params: { postId: id } }) })
|
|
41
|
+
.mutate({
|
|
42
|
+
update: {
|
|
43
|
+
request: requests.updatePostRequest,
|
|
44
|
+
map: (key, changes) => ({ params: { postId: key }, payload: changes }),
|
|
45
|
+
optimistic: false,
|
|
46
|
+
onSuccess: "keep",
|
|
47
|
+
},
|
|
48
|
+
});
|
|
49
|
+
// Written only through named transactions, so it declares no mutations
|
|
50
|
+
const draft = collection(PostSchema, { key: "id" }).load(requests.getPost, {
|
|
51
|
+
byKey: (id) => ({ params: { postId: id } }),
|
|
52
|
+
});
|
|
53
|
+
const transactions = {
|
|
54
|
+
publish: {
|
|
55
|
+
mutationFn: ({ id, mutations }: { id: string; mutations: TransactionWrite[] }) =>
|
|
56
|
+
publish.setPayload({ mutations, idempotencyKey: id }),
|
|
57
|
+
},
|
|
58
|
+
publishAndReload: {
|
|
59
|
+
mutationFn: ({ id, mutations }: { id: string; mutations: TransactionWrite[] }) =>
|
|
60
|
+
publish.setPayload({ mutations, idempotencyKey: id }),
|
|
61
|
+
onSuccess: "refetch" as const,
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
return { collections: { post, draft, remote }, transactions, client };
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const setup = (options: DbOptions = {}) => {
|
|
68
|
+
const { collections, transactions, client } = createCollections();
|
|
69
|
+
const db = createDb(collections, { ...options, transactions });
|
|
70
|
+
const errors: DbErrorEvent[] = [];
|
|
71
|
+
db.onError((event) => errors.push(event));
|
|
72
|
+
return { api: createApi(server), db, errors, client };
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const titles = (posts: Post[] | undefined) => posts?.map((post) => post.title);
|
|
76
|
+
|
|
77
|
+
describe("db [ Transactions ]", () => {
|
|
78
|
+
let context = setup();
|
|
79
|
+
|
|
80
|
+
beforeAll(() => startServer());
|
|
81
|
+
beforeEach(() => {
|
|
82
|
+
resetMocks();
|
|
83
|
+
context = setup();
|
|
84
|
+
});
|
|
85
|
+
afterEach(() => context.db.destroy());
|
|
86
|
+
afterAll(() => stopServer());
|
|
87
|
+
|
|
88
|
+
const loadTeam = async () => {
|
|
89
|
+
context.api.get("/teams/:teamId/full-posts", () => ({ data: { items: [createPost(1), createPost(2)] } }));
|
|
90
|
+
const query = context.db.post.where((post) => eq(post.teamId, 1)).orderBy((post) => post.id);
|
|
91
|
+
const unsubscribe = query.subscribe(() => {});
|
|
92
|
+
await vi.waitFor(() => expect(query.getSnapshot().status).toBe("ready"));
|
|
93
|
+
return { query, unsubscribe };
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
describe("without a name", () => {
|
|
97
|
+
it("shows every write at once and sends them in order through each collection's mutate", async () => {
|
|
98
|
+
const { api, db } = context;
|
|
99
|
+
const { query, unsubscribe } = await loadTeam();
|
|
100
|
+
const order: string[] = [];
|
|
101
|
+
const release = deferred();
|
|
102
|
+
api.patch("/posts/:postId", async ({ params, body }) => {
|
|
103
|
+
order.push(`patch ${params.postId}`);
|
|
104
|
+
await release.promise;
|
|
105
|
+
return { data: createPost(Number(params.postId), body as Partial<Post>) };
|
|
106
|
+
});
|
|
107
|
+
api.post("/posts", ({ body }) => {
|
|
108
|
+
order.push("post");
|
|
109
|
+
return { data: body };
|
|
110
|
+
});
|
|
111
|
+
const transaction = db.transaction((tx) => {
|
|
112
|
+
tx.post.update(1, { title: "One" });
|
|
113
|
+
tx.post.insert(createPost(3, { title: "Three" }));
|
|
114
|
+
});
|
|
115
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["One", "Post 2", "Three"]);
|
|
116
|
+
await flush();
|
|
117
|
+
expect(order).toStrictEqual(["patch 1"]);
|
|
118
|
+
release.resolve();
|
|
119
|
+
expect(await transaction).toMatchObject({ success: true, error: null });
|
|
120
|
+
expect(order).toStrictEqual(["patch 1", "post"]);
|
|
121
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["One", "Post 2", "Three"]);
|
|
122
|
+
expect(typeof transaction.id).toBe("string");
|
|
123
|
+
unsubscribe();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("drops the writes after a failed one and refetches the rows already written", async () => {
|
|
127
|
+
const { api, db, errors } = context;
|
|
128
|
+
const { query, unsubscribe } = await loadTeam();
|
|
129
|
+
api.patch("/posts/:postId", ({ params, body }) =>
|
|
130
|
+
params.postId === "2"
|
|
131
|
+
? { status: 400, data: { message: "No" } }
|
|
132
|
+
: { data: createPost(Number(params.postId), body as Partial<Post>) },
|
|
133
|
+
);
|
|
134
|
+
const fetches = () => api.callsTo("/teams/1/full-posts").length;
|
|
135
|
+
const before = fetches();
|
|
136
|
+
const result = await db.transaction((tx) => {
|
|
137
|
+
tx.post.update(1, { title: "One" });
|
|
138
|
+
tx.post.update(2, { title: "Two" });
|
|
139
|
+
tx.post.delete(1);
|
|
140
|
+
});
|
|
141
|
+
expect(result.success).toBeFalse();
|
|
142
|
+
expect(result.error).toMatchObject({ message: "No" });
|
|
143
|
+
await vi.waitFor(() => expect(fetches()).toBe(before + 1));
|
|
144
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["Post 1", "Post 2"]);
|
|
145
|
+
expect(api.callsTo("/posts/1", "delete")).toHaveLength(0);
|
|
146
|
+
expect(errors.some((event) => event.error instanceof DependencyError)).toBeTrue();
|
|
147
|
+
unsubscribe();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("completes at once without writes, and rejects invalid writes and inserts without a key", async () => {
|
|
151
|
+
const { db, errors } = context;
|
|
152
|
+
expect(await db.transaction(() => {})).toStrictEqual({ success: true, data: [], error: null });
|
|
153
|
+
|
|
154
|
+
const invalid = await db.transaction((tx) => {
|
|
155
|
+
tx.post.insert(createPost(4, { title: "" }));
|
|
156
|
+
});
|
|
157
|
+
expect(invalid.success).toBeFalse();
|
|
158
|
+
expect(errors.some((event) => event.type === "validation")).toBeTrue();
|
|
159
|
+
|
|
160
|
+
const keyless = await db.transaction((tx) => {
|
|
161
|
+
const { id: _id, ...row } = createPost(5);
|
|
162
|
+
tx.post.insert(row as Post);
|
|
163
|
+
});
|
|
164
|
+
expect(keyless).toMatchObject({ success: false });
|
|
165
|
+
expect(String(keyless.error)).toContain("needs its key");
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it("adds no layer for a collection whose writes are not optimistic", async () => {
|
|
169
|
+
const { api, db } = context;
|
|
170
|
+
api.get("/posts/:postId", ({ params }) => ({ data: createPost(Number(params.postId)) }));
|
|
171
|
+
api.patch("/posts/:postId", () => ({ data: null }));
|
|
172
|
+
const one = db.remote.findOne(1);
|
|
173
|
+
const stop = one.subscribe(() => {});
|
|
174
|
+
await vi.waitFor(() => expect(one.getSnapshot().data?.id).toBe(1));
|
|
175
|
+
const transaction = db.transaction((tx) => {
|
|
176
|
+
tx.remote.update(1, { title: "Later" });
|
|
177
|
+
});
|
|
178
|
+
expect(one.getSnapshot().data?.title).toBe("Post 1");
|
|
179
|
+
expect(await transaction).toMatchObject({ success: true });
|
|
180
|
+
expect(one.getSnapshot().data?.title).toBe("Later");
|
|
181
|
+
stop();
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("validates writes with an asynchronous schema", async () => {
|
|
185
|
+
const client = createHttpClient();
|
|
186
|
+
const requests = createRequests(client);
|
|
187
|
+
const asyncSchema: StandardSchemaV1<Post, Post> = {
|
|
188
|
+
"~standard": { version: 1, vendor: "test", validate: async (value) => ({ value: value as Post }) },
|
|
189
|
+
};
|
|
190
|
+
const AsyncPost = collection(asyncSchema, { key: "id" }).mutate({
|
|
191
|
+
insert: { request: requests.createPostRequest, map: (row) => ({ payload: row }) },
|
|
192
|
+
});
|
|
193
|
+
const db = createDb({ post: AsyncPost });
|
|
194
|
+
context.api.post("/posts", ({ body }) => ({ data: body }));
|
|
195
|
+
const result = await db.transaction((tx) => {
|
|
196
|
+
tx.post.insert(createPost(6));
|
|
197
|
+
});
|
|
198
|
+
expect(result.success).toBeTrue();
|
|
199
|
+
db.destroy();
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
describe("with a name", () => {
|
|
204
|
+
it("sends every write in one request with the transaction id and keeps the changes", async () => {
|
|
205
|
+
const { api, db } = context;
|
|
206
|
+
const { query, unsubscribe } = await loadTeam();
|
|
207
|
+
const release = deferred();
|
|
208
|
+
api.post("/publish", async () => {
|
|
209
|
+
await release.promise;
|
|
210
|
+
return { data: { ok: true } };
|
|
211
|
+
});
|
|
212
|
+
const transaction = db.transaction("publish", (tx) => {
|
|
213
|
+
tx.post.update(1, { title: "Published" });
|
|
214
|
+
tx.draft.insert(createPost(9));
|
|
215
|
+
tx.post.delete(2);
|
|
216
|
+
});
|
|
217
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["Published"]);
|
|
218
|
+
expect(db.draft.findOne(9).local().getSnapshot().data?.id).toBe(9);
|
|
219
|
+
release.resolve();
|
|
220
|
+
expect(await transaction).toStrictEqual({ success: true, data: { ok: true }, error: null });
|
|
221
|
+
const [call] = api.callsTo("/publish", "post");
|
|
222
|
+
expect(call.body).toStrictEqual({
|
|
223
|
+
idempotencyKey: transaction.id,
|
|
224
|
+
mutations: [
|
|
225
|
+
{ collection: "post", op: "update", key: 1, values: { title: "Published" } },
|
|
226
|
+
{ collection: "draft", op: "insert", key: 9, values: createPost(9) },
|
|
227
|
+
{ collection: "post", op: "delete", key: 2, values: {} },
|
|
228
|
+
],
|
|
229
|
+
});
|
|
230
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["Published"]);
|
|
231
|
+
expect(api.callsTo("/posts/1", "patch")).toHaveLength(0);
|
|
232
|
+
unsubscribe();
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
it("reverts every write when the request fails and keeps the error as the response gave it", async () => {
|
|
236
|
+
const { api, db } = context;
|
|
237
|
+
const { query, unsubscribe } = await loadTeam();
|
|
238
|
+
api.post("/publish", () => ({ status: 409, data: { message: "Conflict" } }));
|
|
239
|
+
const result = await db.transaction("publish", (tx) => {
|
|
240
|
+
tx.post.update(1, { title: "Published" });
|
|
241
|
+
tx.post.update(2, { title: "Also" });
|
|
242
|
+
});
|
|
243
|
+
expect(result).toMatchObject({ success: false, error: { message: "Conflict" } });
|
|
244
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["Post 1", "Post 2"]);
|
|
245
|
+
unsubscribe();
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("refetches the subsets holding the changed rows with onSuccess refetch", async () => {
|
|
249
|
+
const { api, db } = context;
|
|
250
|
+
const { query, unsubscribe } = await loadTeam();
|
|
251
|
+
api.post("/publish", () => ({ data: { ok: true } }));
|
|
252
|
+
api.get("/teams/:teamId/full-posts", () => ({
|
|
253
|
+
data: { items: [createPost(1, { title: "From server" }), createPost(2)] },
|
|
254
|
+
}));
|
|
255
|
+
api.get("/posts/:postId", ({ params }) => ({ data: createPost(Number(params.postId)) }));
|
|
256
|
+
const result = await db.transaction("publishAndReload", (tx) => {
|
|
257
|
+
tx.post.update(1, { title: "Mine" });
|
|
258
|
+
tx.draft.update(8, { title: "Not held" });
|
|
259
|
+
});
|
|
260
|
+
expect(result.success).toBeTrue();
|
|
261
|
+
expect(titles(query.getSnapshot().data)).toStrictEqual(["From server", "Post 2"]);
|
|
262
|
+
expect(db.draft.findOne(8).local().getSnapshot().data).toBeUndefined();
|
|
263
|
+
unsubscribe();
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
it("keeps a named transaction in the outbox by name and replays it after a restart", async () => {
|
|
267
|
+
const storage = createMemoryStorage();
|
|
268
|
+
const first = setup({ persistence: { storage }, offline: true, tabs: false });
|
|
269
|
+
first.client.appManager.setOnline(false);
|
|
270
|
+
first.db.transaction("publish", (tx) => {
|
|
271
|
+
tx.draft.insert(createPost(7, { title: "Offline" }));
|
|
272
|
+
});
|
|
273
|
+
await flush();
|
|
274
|
+
first.db.destroy();
|
|
275
|
+
|
|
276
|
+
const second = setup({ persistence: { storage }, offline: true, tabs: false });
|
|
277
|
+
const release = deferred();
|
|
278
|
+
const calls: unknown[] = [];
|
|
279
|
+
second.api.post("/publish", async ({ body }) => {
|
|
280
|
+
calls.push(body);
|
|
281
|
+
await release.promise;
|
|
282
|
+
return { data: { ok: true } };
|
|
283
|
+
});
|
|
284
|
+
await second.db.ready;
|
|
285
|
+
// The restored outbox shows the write before it is replayed
|
|
286
|
+
expect(second.db.draft.findOne(7).local().getSnapshot().data?.title).toBe("Offline");
|
|
287
|
+
await vi.waitFor(() => expect(calls).toHaveLength(1));
|
|
288
|
+
expect(calls[0]).toMatchObject({ mutations: [{ collection: "draft", op: "insert", key: 7 }] });
|
|
289
|
+
release.resolve();
|
|
290
|
+
await vi.waitFor(() => expect(second.db.draft.findOne(7).local().getSnapshot().data?.title).toBe("Offline"));
|
|
291
|
+
second.db.destroy();
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("replays an unnamed transaction offline in order and drops the writes after a rejected one", async () => {
|
|
295
|
+
const offline = setup({ offline: { retryDelay: () => 0 }, tabs: false });
|
|
296
|
+
offline.api.patch("/posts/:postId", () => ({ status: 422, data: { message: "Invalid" } }));
|
|
297
|
+
offline.api.post("/posts", ({ body }) => ({ data: body }));
|
|
298
|
+
const result = await offline.db.transaction((tx) => {
|
|
299
|
+
tx.post.update(1, { title: "One" });
|
|
300
|
+
tx.post.insert(createPost(3));
|
|
301
|
+
});
|
|
302
|
+
expect(result).toMatchObject({ success: false, error: { message: "Invalid" } });
|
|
303
|
+
expect(offline.api.callsTo("/posts", "post")).toHaveLength(0);
|
|
304
|
+
offline.db.destroy();
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
it("reports an outbox transaction whose name the db no longer declares", async () => {
|
|
308
|
+
const storage = createMemoryStorage();
|
|
309
|
+
const first = setup({ persistence: { storage }, offline: true, tabs: false });
|
|
310
|
+
first.client.appManager.setOnline(false);
|
|
311
|
+
first.db.transaction("publish", (tx) => {
|
|
312
|
+
tx.post.update(1, { title: "Offline" });
|
|
313
|
+
});
|
|
314
|
+
await flush();
|
|
315
|
+
first.db.destroy();
|
|
316
|
+
|
|
317
|
+
const { collections } = createCollections();
|
|
318
|
+
const db = createDb(collections, { persistence: { storage }, offline: true, tabs: false });
|
|
319
|
+
const errors: DbErrorEvent[] = [];
|
|
320
|
+
db.onError((event) => errors.push(event));
|
|
321
|
+
await db.ready;
|
|
322
|
+
expect(String(errors[0]?.error)).toContain('the transaction "publish"');
|
|
323
|
+
db.destroy();
|
|
324
|
+
});
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
it("types transaction names and the writes each collection allows", () => {
|
|
328
|
+
const { db } = context;
|
|
329
|
+
const check = () => {
|
|
330
|
+
// @ts-expect-error the db declares no transaction of that name
|
|
331
|
+
db.transaction("missing", () => {});
|
|
332
|
+
db.transaction((tx) => {
|
|
333
|
+
// @ts-expect-error `draft` has no mutations, so only named transactions write it
|
|
334
|
+
tx.draft.insert(createPost(1));
|
|
335
|
+
});
|
|
336
|
+
db.transaction("publish", (tx) => {
|
|
337
|
+
tx.draft.update(1, { title: "Any collection" });
|
|
338
|
+
// @ts-expect-error `title` is a string
|
|
339
|
+
tx.post.update(1, { title: 1 });
|
|
340
|
+
});
|
|
341
|
+
};
|
|
342
|
+
expect(check).toBeFunction();
|
|
343
|
+
});
|
|
344
|
+
});
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { collection, createDb, gt, rowType } from "@hyper-fetch/db";
|
|
2
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
3
|
+
|
|
4
|
+
import { createApi, createHttpClient } from "../utils/fixtures";
|
|
5
|
+
|
|
6
|
+
const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
|
|
7
|
+
|
|
8
|
+
type Item = { id: number; group: number; score: number | null; name: string };
|
|
9
|
+
|
|
10
|
+
const item = (id: number, overrides: Partial<Item> = {}): Item => ({
|
|
11
|
+
id,
|
|
12
|
+
group: 1,
|
|
13
|
+
score: id * 10,
|
|
14
|
+
name: `Item ${id}`,
|
|
15
|
+
...overrides,
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const setup = (items: Item[]) => {
|
|
19
|
+
const client = createHttpClient();
|
|
20
|
+
const api = createApi(server);
|
|
21
|
+
const getItems = client.createRequest<{ response: Item[] }>()({ endpoint: "/items" });
|
|
22
|
+
const saveItem = client.createRequest<{ response: Item; payload: Item }>()({ endpoint: "/items", method: "PUT" });
|
|
23
|
+
const deleteItem = client.createRequest<{ response: null }>()({ endpoint: "/items/:id", method: "DELETE" });
|
|
24
|
+
const Items = collection(rowType<Item>(), { key: "id" })
|
|
25
|
+
.load(getItems)
|
|
26
|
+
.ingest(saveItem)
|
|
27
|
+
.mutate({ delete: { request: deleteItem, map: (id) => ({ params: { id } }), onSuccess: "keep" } });
|
|
28
|
+
api.get("/items", () => ({ data: items }));
|
|
29
|
+
api.put("/items", ({ body }) => ({ data: body }));
|
|
30
|
+
api.delete("/items/:id", () => ({ data: null }));
|
|
31
|
+
const db = createDb({ item: Items });
|
|
32
|
+
const save = (row: Item) => saveItem.setPayload(row).send();
|
|
33
|
+
return { db, save };
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const ids = (items: { id: number }[] | undefined) => items?.map((row) => row.id);
|
|
37
|
+
|
|
38
|
+
describe("db [ Windows and ordering ]", () => {
|
|
39
|
+
beforeAll(() => startServer());
|
|
40
|
+
beforeEach(() => resetMocks());
|
|
41
|
+
afterAll(() => stopServer());
|
|
42
|
+
|
|
43
|
+
const open = async (
|
|
44
|
+
db: ReturnType<typeof setup>["db"],
|
|
45
|
+
build: (query: ReturnType<typeof setup>["db"]["item"]) => any,
|
|
46
|
+
) => {
|
|
47
|
+
const query = build(db.item);
|
|
48
|
+
const unsubscribe = query.subscribe(() => {});
|
|
49
|
+
await vi.waitFor(() => expect(query.getSnapshot().status).toBe("ready"));
|
|
50
|
+
return { query, unsubscribe };
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
it("keeps a limited window in step with inserts before, inside and after it", async () => {
|
|
54
|
+
const { db, save } = setup([1, 2, 3, 4].map((id) => item(id)));
|
|
55
|
+
const { query, unsubscribe } = await open(db, (items) => items.orderBy((row) => row.score).limit(3));
|
|
56
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1, 2, 3]);
|
|
57
|
+
|
|
58
|
+
await save(item(0, { score: 0 }));
|
|
59
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([0, 1, 2]);
|
|
60
|
+
await save(item(5, { score: 15 }));
|
|
61
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([0, 1, 5]);
|
|
62
|
+
|
|
63
|
+
// An insert after the window changes nothing, and the result keeps its identity
|
|
64
|
+
const before = query.getSnapshot().data;
|
|
65
|
+
await save(item(9, { score: 90 }));
|
|
66
|
+
expect(query.getSnapshot().data).toBe(before);
|
|
67
|
+
unsubscribe();
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it("backfills the window when a row inside it is deleted or moves out, and ignores deletes outside", async () => {
|
|
71
|
+
const { db, save } = setup([1, 2, 3, 4, 5].map((id) => item(id)));
|
|
72
|
+
const { query, unsubscribe } = await open(db, (items) => items.orderBy((row) => row.score).limit(3));
|
|
73
|
+
|
|
74
|
+
await db.item.delete(2);
|
|
75
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1, 3, 4]);
|
|
76
|
+
const before = query.getSnapshot().data;
|
|
77
|
+
await db.item.delete(5);
|
|
78
|
+
expect(query.getSnapshot().data).toBe(before);
|
|
79
|
+
|
|
80
|
+
await save(item(1, { score: 100 }));
|
|
81
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([3, 4, 1]);
|
|
82
|
+
unsubscribe();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("fills a window that is not full, and handles an empty collection, a large limit and limit 0", async () => {
|
|
86
|
+
const { db, save } = setup([]);
|
|
87
|
+
const { query, unsubscribe } = await open(db, (items) => items.orderBy((row) => row.score).limit(2));
|
|
88
|
+
expect(query.getSnapshot().data).toStrictEqual([]);
|
|
89
|
+
await save(item(1));
|
|
90
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1]);
|
|
91
|
+
|
|
92
|
+
const large = await open(db, (items) => items.orderBy((row) => row.id).limit(50));
|
|
93
|
+
expect(ids(large.query.getSnapshot().data)).toStrictEqual([1]);
|
|
94
|
+
const none = await open(db, (items) => items.orderBy((row) => row.id).limit(0));
|
|
95
|
+
expect(none.query.getSnapshot().data).toStrictEqual([]);
|
|
96
|
+
[unsubscribe, large.unsubscribe, none.unsubscribe].forEach((stop) => stop());
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("breaks ties by key, stably across updates and a delete followed by a reinsert", async () => {
|
|
100
|
+
const { db, save } = setup([3, 1, 2].map((id) => item(id, { score: 5 })));
|
|
101
|
+
const { query, unsubscribe } = await open(db, (items) => items.orderBy((row) => row.score));
|
|
102
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1, 2, 3]);
|
|
103
|
+
await save(item(2, { score: 5, name: "Renamed" }));
|
|
104
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1, 2, 3]);
|
|
105
|
+
await db.item.delete(1);
|
|
106
|
+
await save(item(1, { score: 5 }));
|
|
107
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1, 2, 3]);
|
|
108
|
+
unsubscribe();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it("puts empty values first ascending and last descending, ties broken by key", async () => {
|
|
112
|
+
const { db } = setup([
|
|
113
|
+
item(1, { score: 10 }),
|
|
114
|
+
item(2, { score: null }),
|
|
115
|
+
item(3, { score: -5 }),
|
|
116
|
+
item(4, { score: null }),
|
|
117
|
+
]);
|
|
118
|
+
const asc = await open(db, (items) => items.orderBy((row) => row.score));
|
|
119
|
+
const desc = await open(db, (items) => items.orderBy((row) => row.score, "desc"));
|
|
120
|
+
expect(ids(asc.query.getSnapshot().data)).toStrictEqual([2, 4, 3, 1]);
|
|
121
|
+
expect(ids(desc.query.getSnapshot().data)).toStrictEqual([1, 3, 2, 4]);
|
|
122
|
+
asc.unsubscribe();
|
|
123
|
+
desc.unsubscribe();
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("sorts by several fields in mixed directions and moves a row when its sort field changes", async () => {
|
|
127
|
+
const { db, save } = setup([
|
|
128
|
+
item(1, { group: 2, score: 10 }),
|
|
129
|
+
item(2, { group: 1, score: 10 }),
|
|
130
|
+
item(3, { group: 1, score: 30 }),
|
|
131
|
+
item(4, { group: 2, score: 40 }),
|
|
132
|
+
]);
|
|
133
|
+
const { query, unsubscribe } = await open(db, (items) =>
|
|
134
|
+
items.orderBy((row) => row.group).orderBy((row) => row.score, "desc"),
|
|
135
|
+
);
|
|
136
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([3, 2, 4, 1]);
|
|
137
|
+
await save(item(1, { group: 1, score: 20 }));
|
|
138
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([3, 1, 2, 4]);
|
|
139
|
+
// Insert, update and delete in a row
|
|
140
|
+
await save(item(5, { group: 2, score: 50 }));
|
|
141
|
+
await save(item(5, { group: 1, score: 5 }));
|
|
142
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([3, 1, 2, 5, 4]);
|
|
143
|
+
await db.item.delete(5);
|
|
144
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([3, 1, 2, 4]);
|
|
145
|
+
unsubscribe();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("orders ingested responses by when their requests were sent, not when they arrived", async () => {
|
|
149
|
+
const client = createHttpClient();
|
|
150
|
+
const api = createApi(server);
|
|
151
|
+
const saveItem = client.createRequest<{ response: Item; payload: Item }>()({ endpoint: "/slow", method: "PUT" });
|
|
152
|
+
const db = createDb({ item: collection(rowType<Item>(), { key: "id" }).ingest(saveItem) });
|
|
153
|
+
const release = { first: () => {} };
|
|
154
|
+
api.put("/slow", async ({ body }) => {
|
|
155
|
+
if ((body as Item).name === "Sent first") {
|
|
156
|
+
await new Promise<void>((resolve) => {
|
|
157
|
+
release.first = resolve;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
return { data: body };
|
|
161
|
+
});
|
|
162
|
+
const first = saveItem.setPayload(item(1, { name: "Sent first" })).send();
|
|
163
|
+
await vi.waitFor(() => expect(api.callsTo("/slow", "put")).toHaveLength(1));
|
|
164
|
+
await saveItem.setPayload(item(1, { name: "Sent second" })).send();
|
|
165
|
+
release.first();
|
|
166
|
+
await first;
|
|
167
|
+
expect(db.item.findOne(1).local().getSnapshot().data?.name).toBe("Sent second");
|
|
168
|
+
db.destroy();
|
|
169
|
+
|
|
170
|
+
// A request sent before the db existed counts from when its response arrives
|
|
171
|
+
const early = saveItem.setPayload(item(2, { name: "Sent first" })).send();
|
|
172
|
+
await vi.waitFor(() => expect(api.callsTo("/slow", "put")).toHaveLength(3));
|
|
173
|
+
const later = createDb({ item: collection(rowType<Item>(), { key: "id" }).ingest(saveItem) });
|
|
174
|
+
release.first();
|
|
175
|
+
await early;
|
|
176
|
+
expect(later.item.findOne(2).local().getSnapshot().data?.name).toBe("Sent first");
|
|
177
|
+
later.destroy();
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("adds and removes rows that a change moves into or out of a filter", async () => {
|
|
181
|
+
const { db, save } = setup([1, 2].map((id) => item(id)));
|
|
182
|
+
const { query, unsubscribe } = await open(db, (items) =>
|
|
183
|
+
items.where((row) => gt(row.score, 15)).orderBy((row) => row.id),
|
|
184
|
+
);
|
|
185
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([2]);
|
|
186
|
+
await save(item(1, { score: 50 }));
|
|
187
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1, 2]);
|
|
188
|
+
await save(item(2, { score: 0 }));
|
|
189
|
+
expect(ids(query.getSnapshot().data)).toStrictEqual([1]);
|
|
190
|
+
unsubscribe();
|
|
191
|
+
});
|
|
192
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"noEmit": true,
|
|
5
|
+
"noUnusedLocals": false,
|
|
6
|
+
"noUnusedParameters": false,
|
|
7
|
+
"types": ["vitest/globals", "jest-extended", "@types/node"]
|
|
8
|
+
},
|
|
9
|
+
"include": ["**/*.ts", "**/*.tsx", "../../../global.d.ts", "../../../vitest.d.ts"],
|
|
10
|
+
"exclude": ["node_modules"]
|
|
11
|
+
}
|