@hyper-fetch/hono 9.9.0 โ 10.1.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 +122 -32
- package/__tests__/features/realtime/realtime.react.spec.tsx +226 -0
- package/__tests__/features/realtime/realtime.sse.spec.ts +340 -0
- package/__tests__/features/realtime/realtime.types.spec.ts +140 -0
- package/__tests__/features/realtime/realtime.websocket.spec.ts +414 -0
- package/__tests__/features/schema/schema.types.spec.ts +42 -0
- package/__tests__/utils/realtime-server.ts +333 -0
- package/dist/hono.types.d.ts +58 -2
- package/dist/hono.types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/package.json +6 -2
- package/src/hono.types.ts +78 -6
- package/src/index.ts +1 -1
- package/vite.config.ts +2 -0
package/README.md
CHANGED
|
@@ -1,38 +1,31 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/hono/overview"><img src="https://raw.githubusercontent.com/BetterTyped/hyper-fetch/main/.github/assets/packages/hono.png" alt="Hyper Fetch Hono. Your Hono app. Typed on the client. Route, validator and param types read from typeof app with no codegen and no runtime." /></a>
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
5
|
<p align="center">
|
|
4
|
-
<
|
|
6
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/hono/overview"><b>Quick Start</b></a> ยท
|
|
7
|
+
<a href="https://hyperfetch.bettertyped.com/docs/integrations/hono/overview">Documentation</a> ยท
|
|
8
|
+
<a href="https://hyperfetch.bettertyped.com/docs/api/hono/Types/HonoAppToHyperFetch">API Reference</a> ยท
|
|
9
|
+
<a href="https://github.com/BetterTyped/hyper-fetch">GitHub</a> ยท
|
|
10
|
+
<a href="https://discord.gg/7upC2kVmyM">Discord</a>
|
|
5
11
|
</p>
|
|
6
12
|
|
|
7
13
|
<p align="center">
|
|
8
|
-
<a href="https://github.com/BetterTyped/hyper-fetch">
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
<a href="https://
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
<a href="https://
|
|
15
|
-
<img src="https://img.shields.io/npm/dm/@hyper-fetch/hono?logo=npm" alt="npm downloads" />
|
|
16
|
-
</a>
|
|
17
|
-
<a href="https://bundlephobia.com/package/@hyper-fetch/hono">
|
|
18
|
-
<img src="https://img.shields.io/bundlephobia/minzip/@hyper-fetch/hono?color=64BC4B" alt="bundle size" />
|
|
19
|
-
</a>
|
|
20
|
-
<a href="https://github.com/BetterTyped/hyper-fetch/blob/main/License.md">
|
|
21
|
-
<img src="https://img.shields.io/github/license/BetterTyped/hyper-fetch?color=yellow" alt="license" />
|
|
22
|
-
</a>
|
|
23
|
-
<a href="https://github.com/BetterTyped/hyper-fetch">
|
|
24
|
-
<img src="https://img.shields.io/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" alt="TypeScript" />
|
|
25
|
-
</a>
|
|
26
|
-
<a href="https://hono.dev/">
|
|
27
|
-
<img src="https://img.shields.io/badge/hono-E36002?logo=hono&logoColor=white" alt="Hono" />
|
|
28
|
-
</a>
|
|
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/hono"><img src="https://img.shields.io/npm/v/@hyper-fetch/hono?logo=npm&color=e76f51" alt="npm version" /></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/@hyper-fetch/hono"><img src="https://api.maciejpyrc.com/portfolio/npm/downloads.svg?packages=@hyper-fetch/hono&color=fbc646" alt="Monthly downloads" /></a>
|
|
17
|
+
<a href="https://bundlejs.com/?q=@hyper-fetch/hono"><img src="https://api.maciejpyrc.com/portfolio/npm/size.svg?package=@hyper-fetch/hono&external=@hyper-fetch/core,hono" 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://hyperfetch.bettertyped.com/docs/integrations/hono/overview"><img src="https://img.shields.io/badge/Hono-4%2B-E36002?logo=hono&logoColor=white" alt="Hono" /></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>
|
|
29
21
|
</p>
|
|
30
22
|
|
|
31
23
|
## ๐ About
|
|
32
24
|
|
|
33
|
-
`@hyper-fetch/hono` turns the type of a Hono app into a
|
|
34
|
-
`createSdk` with response, payload, query and param types read straight from your Hono routes and validators
|
|
35
|
-
|
|
25
|
+
`@hyper-fetch/hono` turns the type of a Hono app into a Hyper Fetch SDK schema. Your frontend calls the backend
|
|
26
|
+
through `createSdk` with response, payload, query and param types read straight from your Hono routes and validators,
|
|
27
|
+
and its sockets connect to `upgradeWebSocket()` and `streamSSE()` routes at type-checked paths. It ships types only, so
|
|
28
|
+
nothing from your server ends up in the client bundle.
|
|
36
29
|
|
|
37
30
|
## ๐ฏ Key Capabilities
|
|
38
31
|
|
|
@@ -41,8 +34,10 @@ types only, so nothing from your server ends up in the client bundle.
|
|
|
41
34
|
- ๐ **Validators drive the payload** - `json` and `query` validators type `setPayload()` and `setQueryParams()`
|
|
42
35
|
- ๐งฉ **Mounted routers included** - `app.route()` and `basePath()` prefixes land in the endpoint and the nesting
|
|
43
36
|
- ๐งท **Every path shape** - Optional `:id?` and regex `:id{[0-9]+}` params, `.all()` and `app.on()` get typed accessors
|
|
44
|
-
-
|
|
45
|
-
-
|
|
37
|
+
- ๐ก **Realtime routes too** - `HonoWebSocketPath` rejects socket URLs that match no `upgradeWebSocket()` route
|
|
38
|
+
- ๐ซ **No fake requests** - WebSocket routes stay out of the HTTP SDK, so nobody calls `send()` on them
|
|
39
|
+
- ๐ชถ **Zero runtime** - Type exports only, so it adds no code to your bundle
|
|
40
|
+
- โก **Every HyperFetch feature** - Cache, retries, deduplication, offline replay and React hooks on every route
|
|
46
41
|
|
|
47
42
|
## ๐ Quick Start
|
|
48
43
|
|
|
@@ -68,14 +63,16 @@ import type { AppSchema } from "@my-app/backend";
|
|
|
68
63
|
const client = createClient({ url: "https://api.example.com" });
|
|
69
64
|
const sdk = createSdk<typeof client, AppSchema>(client);
|
|
70
65
|
|
|
66
|
+
// data is { id: string; name: string } | null
|
|
71
67
|
const { data } = await sdk.users.$userId.$get.setParams({ userId: "1" }).send();
|
|
72
68
|
```
|
|
73
69
|
|
|
74
70
|
## ๐ Documentation
|
|
75
71
|
|
|
76
|
-
- [Hono Integration
|
|
77
|
-
- [
|
|
78
|
-
- [
|
|
72
|
+
- **[Hono Integration](https://hyperfetch.bettertyped.com/docs/integrations/hono/overview)** - Setup, routes, validators and path shapes
|
|
73
|
+
- **[Hono Realtime](https://hyperfetch.bettertyped.com/docs/integrations/hono/realtime)** - WebSocket and Server-Sent Events routes
|
|
74
|
+
- **[SDK](https://hyperfetch.bettertyped.com/docs/core/sdk)** - How `createSdk` turns a schema into requests
|
|
75
|
+
- **[API Reference](https://hyperfetch.bettertyped.com/docs/api/hono/Types/HonoAppToHyperFetch)** - Every exported type
|
|
79
76
|
|
|
80
77
|
## ๐ก Examples
|
|
81
78
|
|
|
@@ -104,7 +101,9 @@ export type AppSchema = HonoAppToHyperFetch<typeof app>;
|
|
|
104
101
|
```ts
|
|
105
102
|
const sdk = createSdk<typeof client, AppSchema>(client);
|
|
106
103
|
|
|
104
|
+
// the payload is typed by the json validator
|
|
107
105
|
await sdk.users.$post.setPayload({ name: "Bob" }).send();
|
|
106
|
+
|
|
108
107
|
// kebab-case paths become camelCase properties: GET /auth/google-login
|
|
109
108
|
await sdk.auth.googleLogin.$get.send();
|
|
110
109
|
```
|
|
@@ -119,11 +118,102 @@ import { sdk } from "./api";
|
|
|
119
118
|
export const UserName = ({ userId }: { userId: string }) => {
|
|
120
119
|
const { data, loading } = useFetch(sdk.users.$userId.$get.setParams({ userId }));
|
|
121
120
|
|
|
122
|
-
if (loading) return <
|
|
121
|
+
if (loading) return <Spinner />;
|
|
123
122
|
return <p>{data?.name}</p>;
|
|
124
123
|
};
|
|
125
124
|
```
|
|
126
125
|
|
|
126
|
+
### WebSocket routes with a typed socket SDK
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// backend
|
|
130
|
+
import { createNodeWebSocket } from "@hono/node-ws";
|
|
131
|
+
import type { ListenerModel } from "@hyper-fetch/sockets";
|
|
132
|
+
|
|
133
|
+
const base = new Hono();
|
|
134
|
+
const { upgradeWebSocket } = createNodeWebSocket({ app: base }); // plus injectWebSocket(server) on Node
|
|
135
|
+
|
|
136
|
+
const app = base.get(
|
|
137
|
+
"/chat/:roomId",
|
|
138
|
+
upgradeWebSocket((c) => ({
|
|
139
|
+
onOpen: (_event, ws) => ws.send(JSON.stringify({ topic: "message", data: { text: "Welcome" } })),
|
|
140
|
+
})),
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
export type AppType = typeof app;
|
|
144
|
+
export type ChatSchema = { message: { $listener: ListenerModel<{ response: { text: string }; topic: "message" }> } };
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// frontend
|
|
149
|
+
import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
|
|
150
|
+
import type { HonoWebSocketPath } from "@hyper-fetch/hono";
|
|
151
|
+
|
|
152
|
+
const path: HonoWebSocketPath<AppType> = `/chat/${roomId}`; // "/rooms/1" would not compile
|
|
153
|
+
const socket = new Socket({ url: `wss://api.example.com${path}` });
|
|
154
|
+
const chat = createSocketSdk<typeof socket, ChatSchema>(socket);
|
|
155
|
+
|
|
156
|
+
chat.message.$listener.listen(({ data }) => console.log(data.text));
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Server-Sent Events with named events
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
// backend: named events reach the listeners of that event name, JSON data is parsed
|
|
163
|
+
app.get("/events", (c) =>
|
|
164
|
+
streamSSE(c, async (stream) => {
|
|
165
|
+
await stream.writeSSE({ id: "1", event: "tick", data: JSON.stringify({ symbol: "BTC", price: 100 }) });
|
|
166
|
+
}),
|
|
167
|
+
);
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
// frontend: Node has no global EventSource, so pass the `eventsource` package there
|
|
172
|
+
import { EventSource } from "eventsource";
|
|
173
|
+
import { ServerSentEventsAdapter, Socket } from "@hyper-fetch/sockets";
|
|
174
|
+
|
|
175
|
+
const events = new Socket({
|
|
176
|
+
url: "http://localhost:3000/events",
|
|
177
|
+
adapter: ServerSentEventsAdapter(),
|
|
178
|
+
adapterOptions: { EventSource },
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
events
|
|
182
|
+
.createListener<{ symbol: string; price: number }>()({ topic: "tick" })
|
|
183
|
+
.listen(({ data }) => console.log(data.price));
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
## ๐งฉ Hyper Fetch Ecosystem
|
|
187
|
+
|
|
188
|
+
One typed client for every backend. Swap the adapter and keep the same `createRequest()` everywhere.
|
|
189
|
+
|
|
190
|
+
<table align="center">
|
|
191
|
+
<tr>
|
|
192
|
+
<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>
|
|
193
|
+
<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>
|
|
194
|
+
<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>
|
|
195
|
+
<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>
|
|
196
|
+
<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>
|
|
197
|
+
<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>
|
|
198
|
+
</tr>
|
|
199
|
+
<tr>
|
|
200
|
+
<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>
|
|
201
|
+
<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>
|
|
202
|
+
<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>
|
|
203
|
+
<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>
|
|
204
|
+
<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>
|
|
205
|
+
<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>
|
|
206
|
+
</tr>
|
|
207
|
+
</table>
|
|
208
|
+
|
|
209
|
+
## ๐ Sponsors
|
|
210
|
+
|
|
211
|
+
<p align="center">
|
|
212
|
+
<a href="https://github.com/sponsors/prc5">
|
|
213
|
+
<img src="https://raw.githubusercontent.com/prc5/sponsors/main/packages/other/sponsorkit/sponsors.svg?raw=true" alt="Sponsors" />
|
|
214
|
+
</a>
|
|
215
|
+
</p>
|
|
216
|
+
|
|
127
217
|
## License
|
|
128
218
|
|
|
129
219
|
[Apache-2.0](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vitest-environment jsdom
|
|
3
|
+
*/
|
|
4
|
+
import { useEmitter, useListener } from "@hyper-fetch/react";
|
|
5
|
+
import type { EmitterModel, ListenerModel, SocketSdkInstance } from "@hyper-fetch/sockets";
|
|
6
|
+
import { createSocketSdk, Socket } from "@hyper-fetch/sockets";
|
|
7
|
+
import { cleanup, renderHook, waitFor } from "@testing-library/react";
|
|
8
|
+
import { StrictMode, useEffect } from "react";
|
|
9
|
+
|
|
10
|
+
import type { HonoWebSocketPath } from "../../../src";
|
|
11
|
+
import type { ChatMessage, RealtimeApp, RealtimeServer } from "../../utils/realtime-server";
|
|
12
|
+
import { createRealtimeServer } from "../../utils/realtime-server";
|
|
13
|
+
|
|
14
|
+
type ChatSchema = {
|
|
15
|
+
chat: { $roomId: { $listener: ListenerModel<{ response: ChatMessage; topic: "chat/:roomId" }> } };
|
|
16
|
+
echo: {
|
|
17
|
+
$listener: ListenerModel<{ response: { text: string }; topic: "echo" }>;
|
|
18
|
+
$emitter: EmitterModel<{ payload: { text: string }; topic: "echo" }>;
|
|
19
|
+
};
|
|
20
|
+
rooms: {
|
|
21
|
+
join: { $emitter: EmitterModel<{ payload: { roomId: string }; topic: "rooms/join" }> };
|
|
22
|
+
leave: { $emitter: EmitterModel<{ payload: { roomId: string }; topic: "rooms/leave" }> };
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type ChatSdk = SocketSdkInstance<ChatSchema, Socket>;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Listens to a room of the multiplexed `/ws` route and keeps the server-side subscription in sync with it:
|
|
30
|
+
* joins on mount and on every (re)connection, leaves on unmount and when the room changes.
|
|
31
|
+
*/
|
|
32
|
+
const useRoom = (sdk: ChatSdk, roomId: string, onEvent?: (message: ChatMessage) => void) => {
|
|
33
|
+
const room = useListener(sdk.chat.$roomId.$listener.setParams({ roomId }));
|
|
34
|
+
const { connected } = room;
|
|
35
|
+
|
|
36
|
+
room.onEvent(({ data }) => onEvent?.(data));
|
|
37
|
+
|
|
38
|
+
// The SDK emitters are stable, so they can be used in the effect directly
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
if (!connected) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
sdk.rooms.join.$emitter.emit({ payload: { roomId } });
|
|
44
|
+
return () => sdk.rooms.leave.$emitter.emit({ payload: { roomId } });
|
|
45
|
+
}, [sdk, connected, roomId]);
|
|
46
|
+
|
|
47
|
+
return room;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
describe("Hono realtime [ React ]", () => {
|
|
51
|
+
let server: RealtimeServer;
|
|
52
|
+
let sockets: Socket[] = [];
|
|
53
|
+
|
|
54
|
+
const createApi = (path: HonoWebSocketPath<RealtimeApp> = "/ws") => {
|
|
55
|
+
const socket = new Socket({ url: `${server.wsUrl}${path}`, reconnectTime: 10 });
|
|
56
|
+
sockets.push(socket);
|
|
57
|
+
return { socket, sdk: createSocketSdk<typeof socket, ChatSchema>(socket) };
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
beforeEach(async () => {
|
|
61
|
+
server = createRealtimeServer();
|
|
62
|
+
await server.start();
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
afterEach(async () => {
|
|
66
|
+
cleanup();
|
|
67
|
+
await Promise.all(sockets.map((socket) => socket.disconnect()));
|
|
68
|
+
sockets = [];
|
|
69
|
+
await server.stop();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("when using useListener", () => {
|
|
73
|
+
it("should subscribe on mount and receive the room messages", async () => {
|
|
74
|
+
const { sdk } = createApi();
|
|
75
|
+
|
|
76
|
+
const { result } = renderHook(() => useRoom(sdk, "1"));
|
|
77
|
+
|
|
78
|
+
await waitFor(() => {
|
|
79
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
80
|
+
});
|
|
81
|
+
expect(result.current.connected).toBe(true);
|
|
82
|
+
server.broadcast("1", "hello");
|
|
83
|
+
|
|
84
|
+
await waitFor(() => {
|
|
85
|
+
expect(result.current.data).toStrictEqual({ roomId: "1", text: "hello" });
|
|
86
|
+
});
|
|
87
|
+
expect(typeof result.current.timestamp).toBe("number");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("should move the server-side subscription when the topic params change", async () => {
|
|
91
|
+
const { sdk } = createApi();
|
|
92
|
+
const onEvent = vi.fn();
|
|
93
|
+
|
|
94
|
+
const { result, rerender } = renderHook(({ roomId }) => useRoom(sdk, roomId, onEvent), {
|
|
95
|
+
initialProps: { roomId: "1" },
|
|
96
|
+
});
|
|
97
|
+
await waitFor(() => {
|
|
98
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
rerender({ roomId: "2" });
|
|
102
|
+
|
|
103
|
+
await waitFor(() => {
|
|
104
|
+
expect(server.state.rooms.get("2")?.size).toBe(1);
|
|
105
|
+
expect(server.state.rooms.has("1")).toBe(false);
|
|
106
|
+
});
|
|
107
|
+
server.broadcast("2", "in room 2");
|
|
108
|
+
await waitFor(() => {
|
|
109
|
+
expect(result.current.data).toStrictEqual({ roomId: "2", text: "in room 2" });
|
|
110
|
+
});
|
|
111
|
+
expect(onEvent).toHaveBeenCalledTimes(1);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("should hold exactly one subscription in StrictMode", async () => {
|
|
115
|
+
const { socket, sdk } = createApi();
|
|
116
|
+
const onEvent = vi.fn();
|
|
117
|
+
// Connected before the mount, so StrictMode runs the joining effect twice
|
|
118
|
+
await waitFor(() => {
|
|
119
|
+
expect(socket.adapter.connected).toBe(true);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
const { result } = renderHook(() => useRoom(sdk, "1", onEvent), { wrapper: StrictMode });
|
|
123
|
+
await waitFor(() => {
|
|
124
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
125
|
+
});
|
|
126
|
+
// Frames of one connection are handled in order - once the echo is back, the server saw every effect frame
|
|
127
|
+
const onEcho = vi.fn();
|
|
128
|
+
sdk.echo.$listener.listen(onEcho);
|
|
129
|
+
sdk.echo.$emitter.emit({ payload: { text: "barrier" } });
|
|
130
|
+
await waitFor(() => {
|
|
131
|
+
expect(onEcho).toHaveBeenCalledTimes(1);
|
|
132
|
+
});
|
|
133
|
+
// StrictMode runs the effect twice - the cleanup in between left the room, so one join is left
|
|
134
|
+
expect(server.state.joinBalance.get("1")).toBe(1);
|
|
135
|
+
|
|
136
|
+
server.broadcast("1", "once");
|
|
137
|
+
|
|
138
|
+
await waitFor(() => {
|
|
139
|
+
expect(result.current.data).toStrictEqual({ roomId: "1", text: "once" });
|
|
140
|
+
});
|
|
141
|
+
expect(onEvent).toHaveBeenCalledTimes(1);
|
|
142
|
+
expect(socket.adapter.listeners.get("chat/1")?.size).toBe(1);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("should stop the server-side subscription on unmount", async () => {
|
|
146
|
+
const { socket, sdk } = createApi();
|
|
147
|
+
|
|
148
|
+
const { unmount } = renderHook(() => useRoom(sdk, "1"));
|
|
149
|
+
await waitFor(() => {
|
|
150
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
unmount();
|
|
154
|
+
|
|
155
|
+
await waitFor(() => {
|
|
156
|
+
expect(server.state.rooms.has("1")).toBe(false);
|
|
157
|
+
});
|
|
158
|
+
expect(server.state.joinBalance.get("1")).toBe(0);
|
|
159
|
+
expect(socket.adapter.listeners.get("chat/1")?.size ?? 0).toBe(0);
|
|
160
|
+
// The connection is shared by the app, unmounting one listener keeps it open
|
|
161
|
+
expect(server.state.connections.size).toBe(1);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("should join again after the Hono server restarts", async () => {
|
|
165
|
+
const { sdk } = createApi();
|
|
166
|
+
|
|
167
|
+
const { result } = renderHook(() => useRoom(sdk, "1"));
|
|
168
|
+
await waitFor(() => {
|
|
169
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
await server.stop();
|
|
173
|
+
await waitFor(() => {
|
|
174
|
+
expect(result.current.connected).toBe(false);
|
|
175
|
+
});
|
|
176
|
+
await server.start();
|
|
177
|
+
|
|
178
|
+
await waitFor(() => {
|
|
179
|
+
expect(server.state.rooms.get("1")?.size).toBe(1);
|
|
180
|
+
});
|
|
181
|
+
server.broadcast("1", "back online");
|
|
182
|
+
await waitFor(() => {
|
|
183
|
+
expect(result.current.data).toStrictEqual({ roomId: "1", text: "back online" });
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
describe("when using useEmitter", () => {
|
|
189
|
+
it("should send messages the Hono handler answers", async () => {
|
|
190
|
+
const { sdk } = createApi();
|
|
191
|
+
|
|
192
|
+
const { result } = renderHook(() => ({
|
|
193
|
+
echo: useListener(sdk.echo.$listener),
|
|
194
|
+
emitter: useEmitter(sdk.echo.$emitter),
|
|
195
|
+
}));
|
|
196
|
+
await waitFor(() => {
|
|
197
|
+
expect(result.current.emitter.connected).toBe(true);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
result.current.emitter.emit({ payload: { text: "from react" } });
|
|
201
|
+
|
|
202
|
+
await waitFor(() => {
|
|
203
|
+
expect(result.current.echo.data).toStrictEqual({ text: "from react" });
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
it("should report an emit while disconnected through onEmitError", async () => {
|
|
208
|
+
const { socket, sdk } = createApi();
|
|
209
|
+
await socket.disconnect();
|
|
210
|
+
const onEmitError = vi.fn();
|
|
211
|
+
|
|
212
|
+
const { result } = renderHook(() => {
|
|
213
|
+
const emitter = useEmitter(sdk.echo.$emitter);
|
|
214
|
+
emitter.onEmitError(onEmitError);
|
|
215
|
+
return emitter;
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
result.current.emit({ payload: { text: "lost" } });
|
|
219
|
+
|
|
220
|
+
await waitFor(() => {
|
|
221
|
+
expect(onEmitError).toHaveBeenCalledTimes(1);
|
|
222
|
+
});
|
|
223
|
+
expect(onEmitError.mock.calls[0][0].error.message).toBe("Cannot emit event when connection is not open");
|
|
224
|
+
});
|
|
225
|
+
});
|
|
226
|
+
});
|