@hyper-fetch/db 0.0.0-stage → 1.0.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,337 @@
|
|
|
1
|
+
import { DependencyError, collection, createDb, eq, rowType } from "@hyper-fetch/db";
|
|
2
|
+
import type { DbErrorEvent, StandardSchemaV1 } 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
|
+
createPost,
|
|
11
|
+
createRequests,
|
|
12
|
+
deferred,
|
|
13
|
+
flush,
|
|
14
|
+
} from "../utils/fixtures";
|
|
15
|
+
|
|
16
|
+
const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
|
|
17
|
+
|
|
18
|
+
const byTeam = { teamId: { eq: (teamId: number) => ({ params: { teamId } }), required: true as const } };
|
|
19
|
+
|
|
20
|
+
const setup = () => {
|
|
21
|
+
const client = createHttpClient();
|
|
22
|
+
const requests = createRequests(client);
|
|
23
|
+
const api = createApi(server);
|
|
24
|
+
const base = collection(PostSchema, { key: "id" })
|
|
25
|
+
.load(requests.getTeamFullPosts, { rows: (response) => response.items, where: byTeam })
|
|
26
|
+
.load(requests.getPost, { byKey: (id) => ({ params: { postId: id } }) });
|
|
27
|
+
const Post = base.mutate({
|
|
28
|
+
insert: { request: requests.createPostRequest, map: (row) => ({ payload: row }) },
|
|
29
|
+
update: {
|
|
30
|
+
request: requests.updatePostRequest,
|
|
31
|
+
map: (key, changes, { id }) => ({ params: { postId: key }, payload: { ...changes, updatedAt: id.length } }),
|
|
32
|
+
},
|
|
33
|
+
delete: { request: requests.deletePostRequest, map: (key) => ({ params: { postId: key } }), onSuccess: "keep" },
|
|
34
|
+
});
|
|
35
|
+
const Kept = base.mutate({
|
|
36
|
+
update: {
|
|
37
|
+
request: requests.updatePostRequest,
|
|
38
|
+
map: (key, changes) => ({ params: { postId: key }, payload: changes }),
|
|
39
|
+
onSuccess: "keep",
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
const Refetched = base.mutate({
|
|
43
|
+
update: {
|
|
44
|
+
request: requests.deletePostRequest,
|
|
45
|
+
map: (key) => ({ params: { postId: key } }),
|
|
46
|
+
onSuccess: "refetch",
|
|
47
|
+
},
|
|
48
|
+
insert: {
|
|
49
|
+
request: requests.createPostRequest,
|
|
50
|
+
map: (row) => ({ payload: row }),
|
|
51
|
+
row: (response) => ({ ...response, title: `${response.title}!` }),
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
const Plain = collection(PostSchema, { key: "id" }).mutate({
|
|
55
|
+
update: {
|
|
56
|
+
request: requests.updatePostRequest,
|
|
57
|
+
map: (key, changes) => ({ params: { postId: key }, payload: changes }),
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
const Loose = collection(rowType<Post>(), { key: "id" })
|
|
61
|
+
.load(requests.getTeamFullPosts, { rows: (response) => response.items, where: byTeam })
|
|
62
|
+
.mutate({
|
|
63
|
+
insert: { request: requests.createPostRequest, map: (row) => ({ payload: row }) },
|
|
64
|
+
update: {
|
|
65
|
+
request: requests.updatePostRequest,
|
|
66
|
+
map: (key, changes) => ({ params: { postId: key }, payload: changes }),
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
const errors: DbErrorEvent[] = [];
|
|
70
|
+
const db = createDb({ post: Post, kept: Kept, refetched: Refetched, plain: Plain, loose: Loose });
|
|
71
|
+
db.onError((event) => errors.push(event));
|
|
72
|
+
return { api, db, errors, requests };
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
type Context = ReturnType<typeof setup>;
|
|
76
|
+
|
|
77
|
+
type LiveQueryLike<State> = {
|
|
78
|
+
subscribe(listener: () => void): () => void;
|
|
79
|
+
getSnapshot(): State;
|
|
80
|
+
refetch(): Promise<void>;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const loadTeam = async <State extends { status: string }>(query: LiveQueryLike<State>) => {
|
|
84
|
+
const unsubscribe = query.subscribe(() => {});
|
|
85
|
+
await vi.waitFor(() => expect(query.getSnapshot().status).toBe("ready"));
|
|
86
|
+
return { query, unsubscribe };
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const titles = (state: { data: Post[] | undefined }) => state.data?.map((post) => post.title);
|
|
90
|
+
|
|
91
|
+
describe("db [ Mutations ]", () => {
|
|
92
|
+
let context: Context;
|
|
93
|
+
|
|
94
|
+
beforeAll(() => startServer());
|
|
95
|
+
beforeEach(() => {
|
|
96
|
+
resetMocks();
|
|
97
|
+
context = setup();
|
|
98
|
+
context.api.get("/teams/:teamId/full-posts", () => ({ data: { items: [createPost(1), createPost(2)] } }));
|
|
99
|
+
});
|
|
100
|
+
afterEach(() => context.db.destroy());
|
|
101
|
+
afterAll(() => stopServer());
|
|
102
|
+
|
|
103
|
+
describe("when an update succeeds", () => {
|
|
104
|
+
it("shows the change at once and writes the response", async () => {
|
|
105
|
+
const { api, db } = context;
|
|
106
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
107
|
+
api.patch("/posts/:postId", ({ body }) => ({ data: createPost(1, { ...(body as Partial<Post>), likes: 50 }) }));
|
|
108
|
+
const write = db.post.update(1, { title: "Optimistic" });
|
|
109
|
+
expect(write.id).toBeString();
|
|
110
|
+
expect(titles(query.getSnapshot())).toStrictEqual(["Optimistic", "Post 2"]);
|
|
111
|
+
const result = await write;
|
|
112
|
+
expect(result).toMatchObject({ success: true, error: null });
|
|
113
|
+
expect(query.getSnapshot().data?.[0]).toMatchObject({ title: "Optimistic", likes: 50 });
|
|
114
|
+
expect(api.callsTo("/posts/1", "patch")[0].body).toMatchObject({ title: "Optimistic", updatedAt: 36 });
|
|
115
|
+
unsubscribe();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it("keeps the optimistic change as the server state with onSuccess keep", async () => {
|
|
119
|
+
const { api, db } = context;
|
|
120
|
+
const { query, unsubscribe } = await loadTeam(context.db.kept.where((post) => eq(post.teamId, 1)));
|
|
121
|
+
api.patch("/posts/:postId", () => ({ data: null }));
|
|
122
|
+
await db.kept.update(2, { title: "Kept" });
|
|
123
|
+
expect(titles(query.getSnapshot())).toStrictEqual(["Post 1", "Kept"]);
|
|
124
|
+
unsubscribe();
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("keeps the layer until the refetch wrote its rows with onSuccess refetch", async () => {
|
|
128
|
+
const { api, db } = context;
|
|
129
|
+
const { query, unsubscribe } = await loadTeam(context.db.refetched.where((post) => eq(post.teamId, 1)));
|
|
130
|
+
const seen: (string | undefined)[] = [];
|
|
131
|
+
const stopWatching = query.subscribe(() => seen.push(query.getSnapshot().data?.[0].title));
|
|
132
|
+
api.delete("/posts/:postId", () => ({ data: null }));
|
|
133
|
+
api.get("/teams/:teamId/full-posts", () => ({
|
|
134
|
+
data: { items: [createPost(1, { title: "From server" }), createPost(2)] },
|
|
135
|
+
}));
|
|
136
|
+
await db.refetched.update(1, { title: "Optimistic" });
|
|
137
|
+
expect(titles(query.getSnapshot())).toStrictEqual(["From server", "Post 2"]);
|
|
138
|
+
expect(seen.filter(Boolean)).not.toContain("Post 1");
|
|
139
|
+
stopWatching();
|
|
140
|
+
unsubscribe();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("writes a kept change when no subset holds the row to refetch", async () => {
|
|
144
|
+
const { api, db } = context;
|
|
145
|
+
api.delete("/posts/:postId", () => ({ data: null }));
|
|
146
|
+
api.post("/posts", ({ body }) => ({ data: { ...(body as Post), id: 3 } }));
|
|
147
|
+
await db.refetched.insert(createPost(3));
|
|
148
|
+
const result = await db.refetched.update(3, { title: "Alone" });
|
|
149
|
+
expect(result.success).toBeTrue();
|
|
150
|
+
expect(db.refetched.findOne(3).local().getSnapshot().data?.title).toBe("Alone");
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("ignores a response that is not an object", async () => {
|
|
154
|
+
const { api, db } = context;
|
|
155
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
156
|
+
api.patch("/posts/:postId", () => ({ data: "ok" }));
|
|
157
|
+
await db.post.update(1, { title: "Changed" });
|
|
158
|
+
expect(titles(query.getSnapshot())).toStrictEqual(["Post 1", "Post 2"]);
|
|
159
|
+
unsubscribe();
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
describe("when a write fails", () => {
|
|
164
|
+
it("reverts the change and reports the error", async () => {
|
|
165
|
+
const { api, db, errors } = context;
|
|
166
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
167
|
+
api.patch("/posts/:postId", () => ({ status: 400, data: { message: "Invalid" } }));
|
|
168
|
+
const result = await db.post.update(1, { title: "Rejected" });
|
|
169
|
+
expect(result).toMatchObject({ success: false, error: { message: "Invalid" } });
|
|
170
|
+
expect(titles(query.getSnapshot())).toStrictEqual(["Post 1", "Post 2"]);
|
|
171
|
+
expect(errors).toMatchObject([{ type: "mutation", collection: "post" }]);
|
|
172
|
+
unsubscribe();
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it("sends writes to one row in order and drops the ones built on a failed write", async () => {
|
|
176
|
+
const { api, db } = context;
|
|
177
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
178
|
+
const release = deferred();
|
|
179
|
+
api.patch("/posts/:postId", async () => {
|
|
180
|
+
await release.promise;
|
|
181
|
+
return { status: 400, data: { message: "Invalid" } };
|
|
182
|
+
});
|
|
183
|
+
const first = db.post.update(1, { title: "First" });
|
|
184
|
+
const second = db.post.update(1, { likes: 99 });
|
|
185
|
+
const other = db.post.update(2, { title: "Other row" });
|
|
186
|
+
expect(query.getSnapshot().data?.[0]).toMatchObject({ title: "First", likes: 99 });
|
|
187
|
+
await flush();
|
|
188
|
+
expect(api.callsTo("/posts/1", "patch")).toHaveLength(1);
|
|
189
|
+
release.resolve();
|
|
190
|
+
expect(await first).toMatchObject({ success: false });
|
|
191
|
+
const dropped = await second;
|
|
192
|
+
expect(dropped.error).toBeInstanceOf(DependencyError);
|
|
193
|
+
await other;
|
|
194
|
+
expect(api.callsTo("/posts/1", "patch")).toHaveLength(1);
|
|
195
|
+
expect(query.getSnapshot().data?.[0]).toMatchObject({ title: "Post 1", likes: 1 });
|
|
196
|
+
unsubscribe();
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("fails a write the collection declares no mutation for", async () => {
|
|
200
|
+
const { db } = context;
|
|
201
|
+
const writable = db.kept as unknown as { delete: (key: number) => PromiseLike<{ error: unknown }> };
|
|
202
|
+
const result = await writable.delete(1);
|
|
203
|
+
expect(String(result.error)).toContain("declares no delete mutation");
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
describe("when rows are inserted and deleted", () => {
|
|
208
|
+
it("shows an inserted row in matching lists and writes the server's row", async () => {
|
|
209
|
+
const { api, db } = context;
|
|
210
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
211
|
+
api.post("/posts", ({ body }) => ({ data: { ...(body as Post), likes: 7 } }));
|
|
212
|
+
const write = db.post.insert(createPost(3));
|
|
213
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2, 3]);
|
|
214
|
+
await write;
|
|
215
|
+
expect(query.getSnapshot().data?.[2].likes).toBe(7);
|
|
216
|
+
unsubscribe();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("swaps a temporary key for the server's in one step and keeps the render key", async () => {
|
|
220
|
+
const { api, db } = context;
|
|
221
|
+
const { query, unsubscribe } = await loadTeam(context.db.loose.where((post) => eq(post.teamId, 1)));
|
|
222
|
+
const release = deferred();
|
|
223
|
+
api.post("/posts", async ({ body }) => {
|
|
224
|
+
await release.promise;
|
|
225
|
+
return { data: { ...(body as Post), id: 42 } };
|
|
226
|
+
});
|
|
227
|
+
api.patch("/posts/:postId", ({ params, body }) => ({
|
|
228
|
+
data: createPost(Number(params.postId), body as Partial<Post>),
|
|
229
|
+
}));
|
|
230
|
+
const { id: _id, ...withoutKey } = createPost(0);
|
|
231
|
+
const insert = db.loose.insert(withoutKey as Post);
|
|
232
|
+
const temporary = query.getSnapshot().data![2];
|
|
233
|
+
expect(String(temporary.id)).toStartWith("tmp:");
|
|
234
|
+
const renderKey = db.loose.renderKey(temporary.id);
|
|
235
|
+
const update = db.loose.update(temporary.id, { title: "After insert" });
|
|
236
|
+
|
|
237
|
+
release.resolve();
|
|
238
|
+
await insert;
|
|
239
|
+
await update;
|
|
240
|
+
expect(api.callsTo("/posts", "post")[0].body).not.toHaveProperty("id");
|
|
241
|
+
expect(api.callsTo("/posts/42", "patch")).toHaveLength(1);
|
|
242
|
+
expect(query.getSnapshot().data?.[2]).toMatchObject({ id: 42, title: "After insert" });
|
|
243
|
+
expect(db.loose.renderKey(42)).toBe(renderKey);
|
|
244
|
+
expect(db.loose.findOne(temporary.id).local().getSnapshot().data?.id).toBe(42);
|
|
245
|
+
unsubscribe();
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
it("maps an insert response through row", async () => {
|
|
249
|
+
const { api, db } = context;
|
|
250
|
+
api.post("/posts", ({ body }) => ({ data: body }));
|
|
251
|
+
await db.refetched.insert(createPost(5));
|
|
252
|
+
expect(db.refetched.findOne(5).local().getSnapshot().data?.title).toBe("Post 5!");
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
it("removes a deleted row at once and brings it back when the delete fails", async () => {
|
|
256
|
+
const { api, db } = context;
|
|
257
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
258
|
+
api.delete("/posts/:postId", () => ({ status: 409, data: { message: "Conflict" } }));
|
|
259
|
+
const write = db.post.delete(1);
|
|
260
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([2]);
|
|
261
|
+
await write;
|
|
262
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2]);
|
|
263
|
+
|
|
264
|
+
api.delete("/posts/:postId", () => ({ data: null }));
|
|
265
|
+
await db.post.delete(2);
|
|
266
|
+
expect(query.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1]);
|
|
267
|
+
unsubscribe();
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
it("waits for writes in flight before a refetch of the collection starts", async () => {
|
|
271
|
+
const { api, db } = context;
|
|
272
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
273
|
+
const release = deferred();
|
|
274
|
+
api.patch("/posts/:postId", async () => {
|
|
275
|
+
await release.promise;
|
|
276
|
+
return { data: createPost(1, { title: "Saved" }) };
|
|
277
|
+
});
|
|
278
|
+
const write = db.post.update(1, { title: "Saved" });
|
|
279
|
+
const refetch = query.refetch();
|
|
280
|
+
await flush();
|
|
281
|
+
expect(api.callsTo("/teams/1/full-posts")).toHaveLength(1);
|
|
282
|
+
release.resolve();
|
|
283
|
+
await write;
|
|
284
|
+
await refetch;
|
|
285
|
+
expect(api.callsTo("/teams/1/full-posts")).toHaveLength(2);
|
|
286
|
+
unsubscribe();
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
describe("when writes are validated", () => {
|
|
291
|
+
it("rejects an invalid insert and update without sending them", async () => {
|
|
292
|
+
const { api, db, errors } = context;
|
|
293
|
+
const { query, unsubscribe } = await loadTeam(context.db.post.where((post) => eq(post.teamId, 1)));
|
|
294
|
+
const insert = await db.post.insert(createPost(3, { title: "" }));
|
|
295
|
+
const update = await db.post.update(1, { title: "" });
|
|
296
|
+
expect(insert.success).toBeFalse();
|
|
297
|
+
expect(update.success).toBeFalse();
|
|
298
|
+
expect(errors.map((event) => event.type)).toStrictEqual(["validation", "validation"]);
|
|
299
|
+
expect(api.calls.filter((call) => call.method !== "get")).toHaveLength(0);
|
|
300
|
+
expect(titles(query.getSnapshot())).toStrictEqual(["Post 1", "Post 2"]);
|
|
301
|
+
unsubscribe();
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it("sends an update for a row the db does not hold without validating it", async () => {
|
|
305
|
+
const { api, db } = context;
|
|
306
|
+
api.patch("/posts/:postId", () => ({ data: createPost(9) }));
|
|
307
|
+
const result = await db.plain.update(9, { title: "" });
|
|
308
|
+
expect(result.success).toBeTrue();
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it("waits for an async schema before applying the write", async () => {
|
|
312
|
+
const client = createHttpClient();
|
|
313
|
+
const requests = createRequests(client);
|
|
314
|
+
const AsyncSchema: StandardSchemaV1<Post, Post> = {
|
|
315
|
+
"~standard": {
|
|
316
|
+
version: 1,
|
|
317
|
+
vendor: "test",
|
|
318
|
+
validate: async (value) => {
|
|
319
|
+
const row = value as Post;
|
|
320
|
+
return row.title ? { value: { ...row, title: row.title.trim() } } : { issues: [{ message: "Required" }] };
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
const AsyncPost = collection(AsyncSchema, { key: "id" }).mutate({
|
|
325
|
+
insert: { request: requests.createPostRequest, map: (row) => ({ payload: row }) },
|
|
326
|
+
});
|
|
327
|
+
const db = createDb({ post: AsyncPost });
|
|
328
|
+
context.api.post("/posts", ({ body }) => ({ data: body }));
|
|
329
|
+
const accepted = await db.post.insert(createPost(4, { title: " Trimmed " }));
|
|
330
|
+
const rejected = await db.post.insert(createPost(5, { title: "" }));
|
|
331
|
+
expect(accepted.success).toBeTrue();
|
|
332
|
+
expect(rejected.success).toBeFalse();
|
|
333
|
+
expect(db.post.findOne(4).local().getSnapshot().data?.title).toBe("Trimmed");
|
|
334
|
+
db.destroy();
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
});
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { collection, createDb, eq } from "@hyper-fetch/db";
|
|
2
|
+
import type { StandardSchemaV1 } from "@hyper-fetch/db";
|
|
3
|
+
import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
import { createApi, createHttpClient } from "../utils/fixtures";
|
|
7
|
+
|
|
8
|
+
const { server, startServer, stopServer, resetMocks } = createHttpMockingServer();
|
|
9
|
+
|
|
10
|
+
const UserSchema = z.object({ id: z.number(), name: z.string().min(1) });
|
|
11
|
+
const PostSchema = z.object({ id: z.number(), teamId: z.number(), title: z.string(), author: UserSchema.nullable() });
|
|
12
|
+
type User = z.infer<typeof UserSchema>;
|
|
13
|
+
type Post = z.infer<typeof PostSchema>;
|
|
14
|
+
|
|
15
|
+
const asyncUserSchema: StandardSchemaV1<User, User> = {
|
|
16
|
+
"~standard": {
|
|
17
|
+
version: 1,
|
|
18
|
+
vendor: "test",
|
|
19
|
+
validate: async (value) => ({ value: value as User }),
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const post = (id: number, author: User | null): Post => ({ id, teamId: 1, title: `Post ${id}`, author });
|
|
24
|
+
|
|
25
|
+
const setup = () => {
|
|
26
|
+
const client = createHttpClient();
|
|
27
|
+
const api = createApi(server);
|
|
28
|
+
const getTeamPosts = client.createRequest<{ response: Post[] }>()({ endpoint: "/teams/:teamId/posts" });
|
|
29
|
+
const getUsers = client.createRequest<{ response: User[] }>()({ endpoint: "/users" });
|
|
30
|
+
const createPostRequest = client.createRequest<{ response: Post; payload: Post }>()({
|
|
31
|
+
endpoint: "/posts",
|
|
32
|
+
method: "POST",
|
|
33
|
+
});
|
|
34
|
+
const User = collection(UserSchema, { key: "id", validate: "all" }).load(getUsers);
|
|
35
|
+
const Reviewer = collection(asyncUserSchema, { key: "id", validate: "all" }).load(getUsers);
|
|
36
|
+
const Post = collection(PostSchema, { key: "id" })
|
|
37
|
+
.load(getTeamPosts, { where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } } })
|
|
38
|
+
.normalize(User, (row) => (row.author ? [row.author] : []))
|
|
39
|
+
.normalize(Reviewer, (row) => (row.author ? [row.author] : []))
|
|
40
|
+
.mutate({ insert: { request: createPostRequest, map: (row) => ({ payload: row }) } });
|
|
41
|
+
const db = createDb({ user: User, reviewer: Reviewer, post: Post });
|
|
42
|
+
return { api, db, Post };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
describe("db [ Normalizing on ingest ]", () => {
|
|
46
|
+
beforeAll(() => startServer());
|
|
47
|
+
beforeEach(() => resetMocks());
|
|
48
|
+
afterAll(() => stopServer());
|
|
49
|
+
|
|
50
|
+
it("writes nested rows of loads and mutation responses into their collections", async () => {
|
|
51
|
+
const { api, db } = setup();
|
|
52
|
+
api.get("/teams/:teamId/posts", () => ({
|
|
53
|
+
data: [post(1, { id: 10, name: "Ada" }), post(2, null), post(3, { id: 11, name: "" })],
|
|
54
|
+
}));
|
|
55
|
+
api.post("/posts", ({ body }) => ({ data: body }));
|
|
56
|
+
const errors: unknown[] = [];
|
|
57
|
+
db.onError((event) => errors.push(event));
|
|
58
|
+
|
|
59
|
+
const posts = db.post.where((row) => eq(row.teamId, 1));
|
|
60
|
+
const users = db.user.local();
|
|
61
|
+
const reviewers = db.reviewer.local();
|
|
62
|
+
const stops = [posts.subscribe(() => {}), users.subscribe(() => {}), reviewers.subscribe(() => {})];
|
|
63
|
+
await vi.waitFor(() => expect(posts.getSnapshot().status).toBe("ready"));
|
|
64
|
+
expect(users.getSnapshot().data).toStrictEqual([{ id: 10, name: "Ada" }]);
|
|
65
|
+
expect(errors).toHaveLength(1);
|
|
66
|
+
await vi.waitFor(() => expect(reviewers.getSnapshot().data).toHaveLength(2));
|
|
67
|
+
|
|
68
|
+
await db.post.insert(post(4, { id: 12, name: "Grace" }));
|
|
69
|
+
expect(users.getSnapshot().data?.map((user) => user.name)).toStrictEqual(["Ada", "Grace"]);
|
|
70
|
+
stops.forEach((stop) => stop());
|
|
71
|
+
db.destroy();
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("fails at createDb when a collection normalizes into one the db does not hold", () => {
|
|
75
|
+
const { Post } = setup();
|
|
76
|
+
expect(() => createDb({ post: Post })).toThrow(
|
|
77
|
+
'"post" normalizes into a collection that was not passed to createDb',
|
|
78
|
+
);
|
|
79
|
+
});
|
|
80
|
+
});
|