@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
package/README.md
CHANGED
|
@@ -1,3 +1,181 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://hyperfetch.bettertyped.com/docs/db/overview"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/.github/assets/packages/db.png" alt="Hyper Fetch DB. One source of truth. Live by default. Typed collections fed by your requests and sockets, with live queries, optimistic writes and an offline outbox." /></a>
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="https://hyperfetch.bettertyped.com/docs/db/quick-start"><b>Quick Start</b></a> ·
|
|
7
|
+
<a href="https://hyperfetch.bettertyped.com/docs/db/overview">Documentation</a> ·
|
|
8
|
+
<a href="https://hyperfetch.bettertyped.com/docs/api/db/Functions/createDb">API Reference</a> ·
|
|
9
|
+
<a href="https://github.com/BetterTyped/hyper-fetch">GitHub</a> ·
|
|
10
|
+
<a href="https://discord.gg/7upC2kVmyM">Discord</a>
|
|
11
|
+
</p>
|
|
12
|
+
|
|
13
|
+
<p align="center">
|
|
14
|
+
<a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/github/stars/BetterTyped/hyper-fetch?style=flat&logo=github&color=333" alt="GitHub stars" /></a>
|
|
15
|
+
<a href="https://www.npmjs.com/package/@hyper-fetch/db"><img src="https://img.shields.io/npm/v/@hyper-fetch/db?logo=npm&color=e76f51" alt="npm version" /></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/@hyper-fetch/db"><img src="https://api.maciejpyrc.com/portfolio/npm/downloads.svg?packages=@hyper-fetch/db&color=fbc646" alt="Monthly downloads" /></a>
|
|
17
|
+
<a href="https://bundlejs.com/?q=@hyper-fetch/db"><img src="https://api.maciejpyrc.com/portfolio/npm/size.svg?package=@hyper-fetch/db&external=@hyper-fetch/core,@hyper-fetch/sockets" alt="Bundle size" /></a>
|
|
18
|
+
<a href="https://github.com/BetterTyped/hyper-fetch"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?logo=typescript&logoColor=white" alt="TypeScript" /></a>
|
|
19
|
+
<a href="https://standardschema.dev"><img src="https://img.shields.io/badge/schemas-Standard%20Schema-3B82F6" alt="Standard Schema" /></a>
|
|
20
|
+
<a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md"><img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=blue" alt="License" /></a>
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
## 📖 About
|
|
24
|
+
|
|
25
|
+
`@hyper-fetch/db` keeps your data in typed collections, one row per record, fed by the requests and socket listeners you
|
|
26
|
+
already have. Components query collections instead of endpoints, and every mutation, socket event or ingested response
|
|
27
|
+
updates each query that shows the row. It is for apps where the same data appears in several views, changes from several
|
|
28
|
+
places, or has to work offline.
|
|
29
|
+
|
|
30
|
+
## 🎯 Key Capabilities
|
|
31
|
+
|
|
32
|
+
- 🧭 **Query data, not endpoints** - `db.post.where(...)` picks the loader, sends what the backend serves, filters the
|
|
33
|
+
rest
|
|
34
|
+
- 🔁 **One write, every view** - Mutations, socket events and ingested responses update every live query at once
|
|
35
|
+
- 🛡️ **Rows that never lie** - A loader, sync or mutation whose rows don't match the schema does not compile
|
|
36
|
+
- ⚡ **Optimistic without rollback code** - Writes show instantly and revert exactly what they changed on failure
|
|
37
|
+
- 🕰️ **Late responses can't win** - Writes are ordered per field, by `version` or by when the request was sent
|
|
38
|
+
- 📶 **Offline outbox** - Writes persist, replay in order with idempotency ids, and one tab replays for all
|
|
39
|
+
- 🧩 **REST resources in one line** - `.resource(sdk.posts, { item: "$postId" })` derives loaders and mutations
|
|
40
|
+
- 🔗 **Related data** - Links keep a post and its summary in step, `normalize` stores nested records, joins batch-load
|
|
41
|
+
them
|
|
42
|
+
- 🔥 **Firestore in one call** - `firestoreCollection` from `@hyper-fetch/firebase/db` maps queries and stays live
|
|
43
|
+
- ♾️ **Infinite lists that stay live** - `useLiveInfiniteQuery` pages over held rows and loads backend pages on demand
|
|
44
|
+
- 🧾 **Transactions** - `db.transaction` keeps or reverts several writes together, as one request or in order
|
|
45
|
+
- 🖥️ **Server rendering** - `db.dehydrate()` on the server, `createDb(collections, { state })` and `DbProvider` on the
|
|
46
|
+
client
|
|
47
|
+
- 🔬 **Inspect it in HyperFlow** - `DevtoolsPlugin({ dbs: [db] })` shows collections, plans, subsets and the outbox
|
|
48
|
+
- 🔍 **No hidden magic** - `query.explain()` shows the loader, what is sent, what runs locally and which syncs apply
|
|
49
|
+
- ⚛️ **React ready** - `useLiveQuery` from `@hyper-fetch/react`, no dependency arrays
|
|
50
|
+
|
|
51
|
+
## 🚀 Quick Start
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
npm install @hyper-fetch/core @hyper-fetch/sockets @hyper-fetch/db
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { collection, createDb, eq } from "@hyper-fetch/db";
|
|
59
|
+
|
|
60
|
+
const Post = collection(PostSchema, { key: "id", version: "updatedAt" })
|
|
61
|
+
.load(getTeamPosts, { where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } } })
|
|
62
|
+
.load(getPost, { byKey: (id) => ({ params: { postId: id } }) })
|
|
63
|
+
.sync(onPostChanged, { type: "update" })
|
|
64
|
+
.mutate({
|
|
65
|
+
update: { request: updatePost, map: (key, changes) => ({ params: { postId: key }, payload: changes }) },
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
export const db = createDb({ post: Post });
|
|
69
|
+
|
|
70
|
+
const posts = db.post.where((post) => eq(post.teamId, 1)).orderBy((post) => post.createdAt, "desc");
|
|
71
|
+
const unsubscribe = posts.subscribe(() => render(posts.getSnapshot().data));
|
|
72
|
+
|
|
73
|
+
db.post.update(1, { title: "Renamed" }); // every query showing post 1 updates at once
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## 📚 Documentation
|
|
77
|
+
|
|
78
|
+
- **[Overview](https://hyperfetch.bettertyped.com/docs/db/overview)** - Collections, loaders, syncs and live queries
|
|
79
|
+
- **[Quick Start](https://hyperfetch.bettertyped.com/docs/db/quick-start)** - From a request to a live query
|
|
80
|
+
- **[Related Data](https://hyperfetch.bettertyped.com/docs/db/related-data)** - Links, normalizing and joins
|
|
81
|
+
- **[Firestore](https://hyperfetch.bettertyped.com/docs/db/firestore)** - A whole collection from one call
|
|
82
|
+
- **[Server Rendering](https://hyperfetch.bettertyped.com/docs/db/server-rendering)** - A db per request, hydrated on
|
|
83
|
+
the client
|
|
84
|
+
- **[Transactions](https://hyperfetch.bettertyped.com/docs/db/transactions)** - Several writes kept or reverted together
|
|
85
|
+
- **[useLiveInfiniteQuery](https://hyperfetch.bettertyped.com/docs/react/db/use-live-infinite-query)** - Live infinite
|
|
86
|
+
lists
|
|
87
|
+
- **[API Reference](https://hyperfetch.bettertyped.com/docs/api/db/Functions/createDb)** - Every function and type
|
|
88
|
+
|
|
89
|
+
## 💡 Examples
|
|
90
|
+
|
|
91
|
+
### List and detail without stale copies
|
|
92
|
+
|
|
93
|
+
A list that returns summaries is its own collection. The detail header renders from the summary at once, the body waits
|
|
94
|
+
for the full post, and one listener keeps both current.
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
const PostSummary = collection(PostSummarySchema, { key: "id" })
|
|
98
|
+
.load(getTeamPosts, { where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } } })
|
|
99
|
+
.sync(onPostChanged, { type: "update", row: ({ body, ...changes }) => changes });
|
|
100
|
+
|
|
101
|
+
const Post = collection(PostSchema, { key: "id" })
|
|
102
|
+
.load(getPost, { byKey: (id) => ({ params: { postId: id } }) })
|
|
103
|
+
.sync(onPostChanged, { type: "update" });
|
|
104
|
+
|
|
105
|
+
const db = createDb({ post: Post, postSummary: PostSummary });
|
|
106
|
+
|
|
107
|
+
const header = useLiveQuery(db.postSummary.findOne(postId).local());
|
|
108
|
+
const body = useLiveQuery(db.post.findOne(postId));
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### Joined authors in one request
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
const db = createDb({ postSummary: PostSummary, user: User }); // User loads with `byKeys`
|
|
115
|
+
|
|
116
|
+
const { data } = useLiveQuery(
|
|
117
|
+
db.postSummary.where((post) => eq(post.teamId, teamId)).join("author", db.user, (post) => post.authorId),
|
|
118
|
+
);
|
|
119
|
+
// data?.[0].author: User | undefined
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Paginated lists
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
const Feed = collection(PostSchema, { key: "id" }).load(getFeed, {
|
|
126
|
+
rows: (response) => response.items,
|
|
127
|
+
cursor: (response) => response.next,
|
|
128
|
+
page: (cursor) => ({ queryParams: { cursor } }),
|
|
129
|
+
orderBy: { createdAt: (direction) => ({ queryParams: { sort: `createdAt:${direction}` } }) },
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const { data, hasNextPage, fetchNextPage } = useLiveQuery(db.feed.orderBy((post) => post.createdAt, "desc"));
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Offline writes
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const db = createDb(
|
|
139
|
+
{ post: Post },
|
|
140
|
+
{ offline: true, persistence: { storage: localStorage, scope: user.id, version: 1 } },
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
const created = db.post.insert(draft);
|
|
144
|
+
db.comment.insert(comment, { dependsOn: [created] }); // dropped if the post is rejected
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## 🧩 Hyper Fetch Ecosystem
|
|
148
|
+
|
|
149
|
+
One typed client for every backend. Swap the adapter and keep the same `createRequest()` everywhere.
|
|
150
|
+
|
|
151
|
+
<table align="center">
|
|
152
|
+
<tr>
|
|
153
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/core"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hyper-fetch.svg" width="36" height="36" alt="" /><br /><sub><b>Core</b></sub></a></td>
|
|
154
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/react"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-react.svg" width="36" height="36" alt="" /><br /><sub><b>React</b></sub></a></td>
|
|
155
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/sockets"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-sockets.svg" width="36" height="36" alt="" /><br /><sub><b>Sockets</b></sub></a></td>
|
|
156
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/db"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hyper-fetch.svg" width="36" height="36" alt="" /><br /><sub><b>DB</b></sub></a></td>
|
|
157
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/cli"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-openapi.svg" width="36" height="36" alt="" /><br /><sub><b>OpenAPI CLI</b></sub></a></td>
|
|
158
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-graphql"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-graphql.svg" width="36" height="36" alt="" /><br /><sub><b>GraphQL</b></sub></a></td>
|
|
159
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-trpc"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-trpc.svg" width="36" height="36" alt="" /><br /><sub><b>tRPC</b></sub></a></td>
|
|
160
|
+
</tr>
|
|
161
|
+
<tr>
|
|
162
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-orpc"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc-dark.svg" /><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-orpc.svg" width="36" height="36" alt="" /></picture><br /><sub><b>oRPC</b></sub></a></td>
|
|
163
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hono"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-hono.svg" width="36" height="36" alt="" /><br /><sub><b>Hono</b></sub></a></td>
|
|
164
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/elysia"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-elysia.svg" width="36" height="36" alt="" /><br /><sub><b>Elysia</b></sub></a></td>
|
|
165
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-firebase"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-firebase.svg" width="36" height="36" alt="" /><br /><sub><b>Firebase</b></sub></a></td>
|
|
166
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/adapter-axios"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/integration-axios.svg" width="36" height="36" alt="" /><br /><sub><b>Axios</b></sub></a></td>
|
|
167
|
+
<td align="center" width="110"><a href="https://github.com/BetterTyped/hyper-fetch/tree/main/packages/hyper-flow"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/documentation/static/img/hyper-flow.svg" width="36" height="36" alt="" /><br /><sub><b>HyperFlow</b></sub></a></td>
|
|
168
|
+
</tr>
|
|
169
|
+
</table>
|
|
170
|
+
|
|
171
|
+
## 💖 Sponsors
|
|
172
|
+
|
|
173
|
+
<p align="center">
|
|
174
|
+
<a href="https://github.com/sponsors/prc5">
|
|
175
|
+
<img src="https://raw.githubusercontent.com/prc5/sponsors/main/packages/other/sponsorkit/sponsors.svg?raw=true" alt="Sponsors" />
|
|
176
|
+
</a>
|
|
177
|
+
</p>
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
[Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment node
|
|
3
|
+
*/
|
|
4
|
+
/* oxlint-disable max-params -- route handlers follow the e2e server's signature */
|
|
5
|
+
import { createSdk } from "@hyper-fetch/core";
|
|
6
|
+
import type { RequestModel } from "@hyper-fetch/core";
|
|
7
|
+
import { collection, createDb, eq } from "@hyper-fetch/db";
|
|
8
|
+
import type { DbOptions } from "@hyper-fetch/db";
|
|
9
|
+
import { createE2EServer, createWebsocketE2EServer, waitForConnection } from "@hyper-fetch/testing";
|
|
10
|
+
|
|
11
|
+
import type { Post, PostSummary } from "../utils/fixtures";
|
|
12
|
+
import {
|
|
13
|
+
PostSchema,
|
|
14
|
+
PostSummarySchema,
|
|
15
|
+
createHttpClient,
|
|
16
|
+
createListeners,
|
|
17
|
+
createMemoryStorage,
|
|
18
|
+
createPost,
|
|
19
|
+
createSocket,
|
|
20
|
+
toSummary,
|
|
21
|
+
} from "../utils/fixtures";
|
|
22
|
+
|
|
23
|
+
type Schema = {
|
|
24
|
+
teams: {
|
|
25
|
+
$teamId: {
|
|
26
|
+
posts: { $get: RequestModel<{ endpoint: "/teams/:teamId/posts"; response: PostSummary[] }> };
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
posts: {
|
|
30
|
+
$post: RequestModel<{ endpoint: "/posts"; response: Post; payload: Post }>;
|
|
31
|
+
$postId: {
|
|
32
|
+
$get: RequestModel<{ endpoint: "/posts/:postId"; response: Post }>;
|
|
33
|
+
$patch: RequestModel<{ endpoint: "/posts/:postId"; response: Post; payload: Partial<Post> }>;
|
|
34
|
+
$delete: RequestModel<{ endpoint: "/posts/:postId"; response: null }>;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const http = createE2EServer();
|
|
40
|
+
const ws = createWebsocketE2EServer();
|
|
41
|
+
const posts = new Map<number, Post>();
|
|
42
|
+
let wsUrl = "";
|
|
43
|
+
|
|
44
|
+
const json = (
|
|
45
|
+
res: { writeHead: (status: number, headers: Record<string, string>) => void; end: (body: string) => void },
|
|
46
|
+
status: number,
|
|
47
|
+
data: unknown,
|
|
48
|
+
) => {
|
|
49
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
50
|
+
res.end(JSON.stringify(data));
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** A small backend: REST routes that change an in-memory table and broadcast every change over the socket */
|
|
54
|
+
const startBackend = async () => {
|
|
55
|
+
http.route("GET", "/teams/:teamId/posts", (_req, res, _body, params) => {
|
|
56
|
+
json(res, 200, [...posts.values()].filter((post) => post.teamId === Number(params.teamId)).map(toSummary));
|
|
57
|
+
});
|
|
58
|
+
http.route("GET", "/posts/:postId", (_req, res, _body, params) => {
|
|
59
|
+
const post = posts.get(Number(params.postId));
|
|
60
|
+
json(res, post ? 200 : 404, post ?? { message: "Not found" });
|
|
61
|
+
});
|
|
62
|
+
http.route("POST", "/posts", (_req, res, body) => {
|
|
63
|
+
const post = JSON.parse(body.toString()) as Post;
|
|
64
|
+
posts.set(post.id, post);
|
|
65
|
+
ws.sendToAll(`teams/${post.teamId}/posts/created`, post);
|
|
66
|
+
json(res, 200, post);
|
|
67
|
+
});
|
|
68
|
+
http.route("PATCH", "/posts/:postId", (_req, res, body, params) => {
|
|
69
|
+
const current = posts.get(Number(params.postId));
|
|
70
|
+
if (!current) {
|
|
71
|
+
json(res, 404, { message: "Not found" });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const changes = JSON.parse(body.toString()) as Partial<Post>;
|
|
75
|
+
if (changes.title === "") {
|
|
76
|
+
json(res, 422, { message: "Title is required" });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const next = { ...current, ...changes, updatedAt: current.updatedAt + 1 };
|
|
80
|
+
posts.set(next.id, next);
|
|
81
|
+
ws.sendToAll(`teams/${next.teamId}/posts/changed`, next);
|
|
82
|
+
json(res, 200, next);
|
|
83
|
+
});
|
|
84
|
+
http.route("DELETE", "/posts/:postId", (_req, res, _body, params) => {
|
|
85
|
+
const current = posts.get(Number(params.postId));
|
|
86
|
+
posts.delete(Number(params.postId));
|
|
87
|
+
if (current) {
|
|
88
|
+
ws.sendToAll(`teams/${current.teamId}/posts/deleted`, { id: current.id });
|
|
89
|
+
}
|
|
90
|
+
json(res, 200, null);
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** One running app: its own client, socket and db */
|
|
95
|
+
const createApp = async (options: DbOptions = {}) => {
|
|
96
|
+
const client = createHttpClient(http.getUrl());
|
|
97
|
+
const sdk = createSdk<typeof client, Schema>(client);
|
|
98
|
+
const socket = createSocket(wsUrl);
|
|
99
|
+
const listeners = createListeners(socket);
|
|
100
|
+
const byTeam = { teamId: { eq: (teamId: number) => ({ params: { teamId } }) } };
|
|
101
|
+
|
|
102
|
+
const Post = collection(PostSchema, { key: "id", version: "updatedAt" }).resource(sdk.posts, {
|
|
103
|
+
item: "$postId",
|
|
104
|
+
list: false,
|
|
105
|
+
});
|
|
106
|
+
const PostSummaryCollection = collection(PostSummarySchema, { key: "id", version: "updatedAt" })
|
|
107
|
+
.load(sdk.teams.$teamId.posts.$get, {
|
|
108
|
+
where: { teamId: { eq: (teamId) => ({ params: { teamId } }), required: true } },
|
|
109
|
+
})
|
|
110
|
+
.sync(listeners.onPostCreated, { type: "insert", where: byTeam, row: ({ body: _body, ...summary }) => summary })
|
|
111
|
+
.sync(listeners.onPostChanged, { type: "update", where: byTeam, row: ({ body: _body, ...changes }) => changes })
|
|
112
|
+
.sync(listeners.onPostDeleted, { type: "delete", where: byTeam });
|
|
113
|
+
const PostLive = Post.sync(listeners.onPostChanged, { type: "update", where: byTeam });
|
|
114
|
+
|
|
115
|
+
const db = createDb({ post: PostLive, postSummary: PostSummaryCollection }, options);
|
|
116
|
+
await waitForConnection(socket);
|
|
117
|
+
return { client, socket, db };
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
describe("E2E [ db ]", () => {
|
|
121
|
+
beforeAll(async () => {
|
|
122
|
+
wsUrl = await ws.startServer();
|
|
123
|
+
await startBackend();
|
|
124
|
+
await http.startServer();
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
beforeEach(() => {
|
|
128
|
+
posts.clear();
|
|
129
|
+
[createPost(1), createPost(2), createPost(3, { teamId: 2 })].forEach((post) => posts.set(post.id, post));
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
afterAll(async () => {
|
|
133
|
+
await http.stopServer();
|
|
134
|
+
await ws.stopServer();
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("keeps two apps in step through the backend's socket events", async () => {
|
|
138
|
+
const alice = await createApp();
|
|
139
|
+
const bob = await createApp();
|
|
140
|
+
|
|
141
|
+
const aliceList = alice.db.postSummary.where((post) => eq(post.teamId, 1)).orderBy((post) => post.id);
|
|
142
|
+
const bobList = bob.db.postSummary.where((post) => eq(post.teamId, 1)).orderBy((post) => post.id);
|
|
143
|
+
const stopAlice = aliceList.subscribe(() => {});
|
|
144
|
+
const stopBob = bobList.subscribe(() => {});
|
|
145
|
+
await vi.waitFor(() => expect(aliceList.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2]));
|
|
146
|
+
await vi.waitFor(() => expect(bobList.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2]));
|
|
147
|
+
|
|
148
|
+
const created = await alice.db.post.insert(createPost(4));
|
|
149
|
+
expect(created.success).toBeTrue();
|
|
150
|
+
await vi.waitFor(() => expect(bobList.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 2, 4]));
|
|
151
|
+
|
|
152
|
+
await alice.db.post.update(1, { title: "Renamed by Alice" });
|
|
153
|
+
await vi.waitFor(() => expect(bobList.getSnapshot().data?.[0].title).toBe("Renamed by Alice"));
|
|
154
|
+
|
|
155
|
+
await bob.db.post.delete(2);
|
|
156
|
+
await vi.waitFor(() => expect(aliceList.getSnapshot().data?.map((post) => post.id)).toStrictEqual([1, 4]));
|
|
157
|
+
|
|
158
|
+
stopAlice();
|
|
159
|
+
stopBob();
|
|
160
|
+
alice.db.destroy();
|
|
161
|
+
bob.db.destroy();
|
|
162
|
+
await alice.socket.disconnect();
|
|
163
|
+
await bob.socket.disconnect();
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("shows the list's fields at once on the detail screen and loads the rest", async () => {
|
|
167
|
+
const app = await createApp();
|
|
168
|
+
const list = app.db.postSummary.where((post) => eq(post.teamId, 1));
|
|
169
|
+
const stopList = list.subscribe(() => {});
|
|
170
|
+
await vi.waitFor(() => expect(list.getSnapshot().status).toBe("ready"));
|
|
171
|
+
|
|
172
|
+
const header = app.db.postSummary.findOne(1).local();
|
|
173
|
+
const body = app.db.post.findOne(1);
|
|
174
|
+
const stopHeader = header.subscribe(() => {});
|
|
175
|
+
const stopBody = body.subscribe(() => {});
|
|
176
|
+
expect(header.getSnapshot().data?.title).toBe("Post 1");
|
|
177
|
+
expect(body.getSnapshot().status).toBe("loading");
|
|
178
|
+
await vi.waitFor(() => expect(body.getSnapshot().data?.body).toBe("Body of post 1"));
|
|
179
|
+
|
|
180
|
+
await app.db.post.update(1, { title: "Live title" });
|
|
181
|
+
await vi.waitFor(() => expect(header.getSnapshot().data?.title).toBe("Live title"));
|
|
182
|
+
|
|
183
|
+
stopList();
|
|
184
|
+
stopHeader();
|
|
185
|
+
stopBody();
|
|
186
|
+
app.db.destroy();
|
|
187
|
+
await app.socket.disconnect();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("joins rows loaded by key and updates them with writes and socket events", async () => {
|
|
191
|
+
const alice = await createApp();
|
|
192
|
+
const bob = await createApp();
|
|
193
|
+
const list = alice.db.postSummary
|
|
194
|
+
.where((post) => eq(post.teamId, 1))
|
|
195
|
+
.orderBy((post) => post.id)
|
|
196
|
+
.join("full", alice.db.post, (post) => post.id);
|
|
197
|
+
const stop = list.subscribe(() => {});
|
|
198
|
+
await vi.waitFor(() =>
|
|
199
|
+
expect(list.getSnapshot().data?.map((post) => post.full?.body)).toStrictEqual([
|
|
200
|
+
"Body of post 1",
|
|
201
|
+
"Body of post 2",
|
|
202
|
+
]),
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
await alice.db.post.update(2, { body: "Edited by Alice" });
|
|
206
|
+
expect(list.getSnapshot().data?.[1].full?.body).toBe("Edited by Alice");
|
|
207
|
+
|
|
208
|
+
await bob.db.post.update(1, { title: "Renamed by Bob" });
|
|
209
|
+
await vi.waitFor(() => expect(list.getSnapshot().data?.[0].title).toBe("Renamed by Bob"));
|
|
210
|
+
// The joined post was read by key, and its team's subscription keeps it live too
|
|
211
|
+
await vi.waitFor(() => expect(list.getSnapshot().data?.[0].full?.title).toBe("Renamed by Bob"));
|
|
212
|
+
|
|
213
|
+
stop();
|
|
214
|
+
alice.db.destroy();
|
|
215
|
+
bob.db.destroy();
|
|
216
|
+
await alice.socket.disconnect();
|
|
217
|
+
await bob.socket.disconnect();
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("reverts a rejected write and reports it", async () => {
|
|
221
|
+
const app = await createApp();
|
|
222
|
+
const detail = app.db.post.findOne(1);
|
|
223
|
+
const stop = detail.subscribe(() => {});
|
|
224
|
+
await vi.waitFor(() => expect(detail.getSnapshot().data?.title).toBe("Post 1"));
|
|
225
|
+
const errors: unknown[] = [];
|
|
226
|
+
app.db.onError((event) => errors.push(event));
|
|
227
|
+
const result = await app.db.post.update(1, { title: "" });
|
|
228
|
+
expect(result.success).toBeFalse();
|
|
229
|
+
expect(detail.getSnapshot().data?.title).toBe("Post 1");
|
|
230
|
+
expect(errors).toHaveLength(1);
|
|
231
|
+
stop();
|
|
232
|
+
app.db.destroy();
|
|
233
|
+
await app.socket.disconnect();
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it("replays offline writes after a restart and restores persisted rows", async () => {
|
|
237
|
+
const storage = createMemoryStorage();
|
|
238
|
+
const first = await createApp({ offline: { retryDelay: () => 10 }, persistence: { storage }, tabs: false });
|
|
239
|
+
const list = first.db.postSummary.where((post) => eq(post.teamId, 1));
|
|
240
|
+
const stopList = list.subscribe(() => {});
|
|
241
|
+
await vi.waitFor(() => expect(list.getSnapshot().status).toBe("ready"));
|
|
242
|
+
const detail = first.db.post.findOne(1);
|
|
243
|
+
const stopDetail = detail.subscribe(() => {});
|
|
244
|
+
await vi.waitFor(() => expect(detail.getSnapshot().data?.id).toBe(1));
|
|
245
|
+
first.client.appManager.setOnline(false);
|
|
246
|
+
first.db.post.update(1, { title: "Written offline" });
|
|
247
|
+
await new Promise((resolve) => {
|
|
248
|
+
setTimeout(resolve, 20);
|
|
249
|
+
});
|
|
250
|
+
expect(posts.get(1)?.title).toBe("Post 1");
|
|
251
|
+
stopList();
|
|
252
|
+
stopDetail();
|
|
253
|
+
first.db.destroy();
|
|
254
|
+
await first.socket.disconnect();
|
|
255
|
+
|
|
256
|
+
const second = await createApp({ offline: { retryDelay: () => 10 }, persistence: { storage }, tabs: false });
|
|
257
|
+
const restored = second.db.postSummary.where((post) => eq(post.teamId, 1));
|
|
258
|
+
const stopRestored = restored.subscribe(() => {});
|
|
259
|
+
await second.db.ready;
|
|
260
|
+
await vi.waitFor(() => expect(posts.get(1)?.title).toBe("Written offline"), { timeout: 3000 });
|
|
261
|
+
await vi.waitFor(
|
|
262
|
+
() => expect(restored.getSnapshot().data?.find((post) => post.id === 1)?.title).toBe("Written offline"),
|
|
263
|
+
{ timeout: 3000 },
|
|
264
|
+
);
|
|
265
|
+
stopRestored();
|
|
266
|
+
second.db.destroy();
|
|
267
|
+
await second.socket.disconnect();
|
|
268
|
+
});
|
|
269
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { relayConnection } from "@hyper-fetch/db";
|
|
2
|
+
import type { RelayConnection } from "@hyper-fetch/db";
|
|
3
|
+
|
|
4
|
+
type Post = { id: string };
|
|
5
|
+
type Response = { posts: RelayConnection<Post> };
|
|
6
|
+
|
|
7
|
+
describe("relayConnection", () => {
|
|
8
|
+
const { rows, cursor } = relayConnection((response: Response) => response.posts);
|
|
9
|
+
|
|
10
|
+
it("reads the nodes of a connection and skips empty edges", () => {
|
|
11
|
+
const response: Response = {
|
|
12
|
+
posts: { edges: [{ node: { id: "a" } }, null], pageInfo: { hasNextPage: true, endCursor: "a" } },
|
|
13
|
+
};
|
|
14
|
+
expect(rows(response)).toStrictEqual([{ id: "a" }]);
|
|
15
|
+
expect(cursor(response)).toBe("a");
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it("has no next cursor on the last page or without an end cursor", () => {
|
|
19
|
+
expect(cursor({ posts: { edges: [], pageInfo: { hasNextPage: false, endCursor: "z" } } })).toBeNull();
|
|
20
|
+
expect(cursor({ posts: { edges: null, pageInfo: { hasNextPage: true } } })).toBeNull();
|
|
21
|
+
expect(rows({ posts: { edges: null, pageInfo: { hasNextPage: true } } })).toStrictEqual([]);
|
|
22
|
+
});
|
|
23
|
+
});
|