@hyper-fetch/hono 9.8.1 → 10.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 +70 -3
- package/__tests__/features/inputs/inputs.sdk.spec.ts +113 -0
- package/__tests__/features/inputs/inputs.types.spec.ts +87 -0
- package/__tests__/features/paths/paths.sdk.spec.ts +159 -0
- package/__tests__/features/paths/paths.types.spec.ts +223 -0
- 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/responses/responses.sdk.spec.ts +149 -0
- package/__tests__/features/responses/responses.types.spec.ts +107 -0
- package/__tests__/features/schema/schema.types.spec.ts +42 -0
- package/__tests__/utils/inputs.app.ts +57 -0
- package/__tests__/utils/paths.app.ts +31 -0
- package/__tests__/utils/realtime-server.ts +333 -0
- package/__tests__/utils/responses.app.ts +54 -0
- package/__tests__/utils/server.ts +18 -0
- package/dist/hono.types.d.ts +105 -10
- 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 +162 -26
- package/src/index.ts +1 -1
- package/vite.config.ts +7 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { createClient, createSdk } from "@hyper-fetch/core";
|
|
2
|
+
import type { ClientInstance, ExtractClientType, ExtractEndpointType, ExtractResponseType } from "@hyper-fetch/core";
|
|
3
|
+
import { Hono } from "hono";
|
|
4
|
+
import { expectTypeOf } from "vitest";
|
|
5
|
+
|
|
6
|
+
import type { HonoAppToHyperFetch } from "../../../src";
|
|
7
|
+
import type { pathsApp, rootOptionalApp } from "../../utils/paths.app";
|
|
8
|
+
|
|
9
|
+
type Schema = HonoAppToHyperFetch<typeof pathsApp>;
|
|
10
|
+
|
|
11
|
+
describe("HonoAppToHyperFetch [ Optional params ]", () => {
|
|
12
|
+
it("should add a route with an optional param both without and with the param", () => {
|
|
13
|
+
expectTypeOf<keyof Schema["files"]>().toEqualTypeOf<"$get" | "$fileId">();
|
|
14
|
+
expectTypeOf<ExtractEndpointType<Schema["files"]["$get"]>>().toEqualTypeOf<"/files">();
|
|
15
|
+
expectTypeOf<ExtractEndpointType<Schema["files"]["$fileId"]["$get"]>>().toEqualTypeOf<"/files/:fileId">();
|
|
16
|
+
expectTypeOf<ExtractResponseType<Schema["files"]["$get"]>>().toEqualTypeOf<{ fileId: string | null }>();
|
|
17
|
+
expect(true).toBe(true);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it("should add every prefix of a route with several optional params", () => {
|
|
21
|
+
type Major = Schema["versions"]["$major"];
|
|
22
|
+
|
|
23
|
+
expectTypeOf<keyof Schema["versions"]>().toEqualTypeOf<"$major">();
|
|
24
|
+
expectTypeOf<keyof Major>().toEqualTypeOf<"$get" | "$minor">();
|
|
25
|
+
expectTypeOf<keyof Major["$minor"]>().toEqualTypeOf<"$get" | "$patch">();
|
|
26
|
+
expectTypeOf<ExtractEndpointType<Major["$get"]>>().toEqualTypeOf<"/versions/:major">();
|
|
27
|
+
expectTypeOf<ExtractEndpointType<Major["$minor"]["$get"]>>().toEqualTypeOf<"/versions/:major/:minor">();
|
|
28
|
+
expectTypeOf<
|
|
29
|
+
ExtractEndpointType<Major["$minor"]["$patch"]["$get"]>
|
|
30
|
+
>().toEqualTypeOf<"/versions/:major/:minor/:patch">();
|
|
31
|
+
expect(true).toBe(true);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("should put the route without an optional root param at the top level", () => {
|
|
35
|
+
type RootSchema = HonoAppToHyperFetch<typeof rootOptionalApp>;
|
|
36
|
+
|
|
37
|
+
expectTypeOf<keyof RootSchema>().toEqualTypeOf<"$get" | "$lang">();
|
|
38
|
+
expectTypeOf<ExtractEndpointType<RootSchema["$get"]>>().toEqualTypeOf<"/">();
|
|
39
|
+
expectTypeOf<ExtractEndpointType<RootSchema["$lang"]["$get"]>>().toEqualTypeOf<"/:lang">();
|
|
40
|
+
expect(true).toBe(true);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it("should not keep keys or params with the optional marker", () => {
|
|
44
|
+
// @ts-expect-error - the optional param is split into two routes
|
|
45
|
+
type OptionalKey = Schema["files"]["$fileId?"];
|
|
46
|
+
|
|
47
|
+
expectTypeOf<OptionalKey>().toBeAny();
|
|
48
|
+
expect(true).toBe(true);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("HonoAppToHyperFetch [ Regex params ]", () => {
|
|
53
|
+
it("should drop the pattern from the key and the endpoint", () => {
|
|
54
|
+
expectTypeOf<keyof Schema["posts"]>().toEqualTypeOf<"$postId">();
|
|
55
|
+
expectTypeOf<ExtractEndpointType<Schema["posts"]["$postId"]["$get"]>>().toEqualTypeOf<"/posts/:postId">();
|
|
56
|
+
expect(true).toBe(true);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("should drop a pattern that holds braces of its own", () => {
|
|
60
|
+
expectTypeOf<keyof Schema["archive"]>().toEqualTypeOf<"$year">();
|
|
61
|
+
expectTypeOf<
|
|
62
|
+
ExtractEndpointType<Schema["archive"]["$year"]["$slug"]["$get"]>
|
|
63
|
+
>().toEqualTypeOf<"/archive/:year/:slug">();
|
|
64
|
+
expect(true).toBe(true);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it("should drop a pattern that holds a slash", () => {
|
|
68
|
+
const app = new Hono().get("/docs/:path{.+/.+}/raw", (c) => c.json({ path: c.req.param("path") }));
|
|
69
|
+
type DocsSchema = HonoAppToHyperFetch<typeof app>;
|
|
70
|
+
|
|
71
|
+
expectTypeOf<keyof DocsSchema["docs"]>().toEqualTypeOf<"$path">();
|
|
72
|
+
expectTypeOf<ExtractEndpointType<DocsSchema["docs"]["$path"]["raw"]["$get"]>>().toEqualTypeOf<"/docs/:path/raw">();
|
|
73
|
+
expect(true).toBe(true);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("should split an optional regex param into two routes", () => {
|
|
77
|
+
const app = new Hono().get("/pages/:page{[0-9]+}?", (c) => c.json({ page: c.req.param("page") ?? "1" }));
|
|
78
|
+
type PagesSchema = HonoAppToHyperFetch<typeof app>;
|
|
79
|
+
|
|
80
|
+
expectTypeOf<keyof PagesSchema["pages"]>().toEqualTypeOf<"$get" | "$page">();
|
|
81
|
+
expectTypeOf<ExtractEndpointType<PagesSchema["pages"]["$page"]["$get"]>>().toEqualTypeOf<"/pages/:page">();
|
|
82
|
+
expect(true).toBe(true);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe("HonoAppToHyperFetch [ Methods ]", () => {
|
|
87
|
+
it("should expand an .all() route into every standard method", () => {
|
|
88
|
+
expectTypeOf<keyof Schema["echo"]>().toEqualTypeOf<
|
|
89
|
+
"$get" | "$post" | "$put" | "$delete" | "$options" | "$patch" | "$query"
|
|
90
|
+
>();
|
|
91
|
+
expectTypeOf<ExtractResponseType<Schema["echo"]["$post"]>>().toEqualTypeOf<{ method: string }>();
|
|
92
|
+
expectTypeOf<ExtractEndpointType<Schema["echo"]["$delete"]>>().toEqualTypeOf<"/echo">();
|
|
93
|
+
expect(true).toBe(true);
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("should not keep the $all key Hono stores .all() routes under", () => {
|
|
97
|
+
// @ts-expect-error - ALL is not an HTTP method a client can send
|
|
98
|
+
type AllKey = Schema["echo"]["$all"];
|
|
99
|
+
|
|
100
|
+
expectTypeOf<AllKey>().toBeAny();
|
|
101
|
+
expect(true).toBe(true);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("should keep a method registered next to an .all() route on the same path", () => {
|
|
105
|
+
const app = new Hono()
|
|
106
|
+
.all("/hook", (c) => c.json({ any: true as const }))
|
|
107
|
+
.get("/hook", (c) => c.json({ read: true as const }));
|
|
108
|
+
type HookSchema = HonoAppToHyperFetch<typeof app>;
|
|
109
|
+
|
|
110
|
+
expectTypeOf<ExtractResponseType<HookSchema["hook"]["$get"]>>().toEqualTypeOf<{ read: true }>();
|
|
111
|
+
expectTypeOf<ExtractResponseType<HookSchema["hook"]["$post"]>>().toEqualTypeOf<{ any: true }>();
|
|
112
|
+
expect(true).toBe(true);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it("should add one key per method of an app.on() route with several methods", () => {
|
|
116
|
+
expectTypeOf<keyof Schema["items"]["$itemId"]>().toEqualTypeOf<"$put" | "$patch">();
|
|
117
|
+
expectTypeOf<ExtractEndpointType<Schema["items"]["$itemId"]["$patch"]>>().toEqualTypeOf<"/items/:itemId">();
|
|
118
|
+
expect(true).toBe(true);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("should add one route per path of an app.on() route with several paths", () => {
|
|
122
|
+
expectTypeOf<ExtractEndpointType<Schema["health"]["$get"]>>().toEqualTypeOf<"/health">();
|
|
123
|
+
expectTypeOf<ExtractEndpointType<Schema["status"]["$get"]>>().toEqualTypeOf<"/status">();
|
|
124
|
+
expectTypeOf<ExtractResponseType<Schema["status"]["$get"]>>().toEqualTypeOf<{ up: true }>();
|
|
125
|
+
expect(true).toBe(true);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("should keep a custom method of app.on()", () => {
|
|
129
|
+
const app = new Hono().on("PURGE", "/cache", (c) => c.json({ purged: true as const }));
|
|
130
|
+
type CacheSchema = HonoAppToHyperFetch<typeof app>;
|
|
131
|
+
|
|
132
|
+
expectTypeOf<keyof CacheSchema["cache"]>().toEqualTypeOf<"$purge">();
|
|
133
|
+
expect(true).toBe(true);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it("should merge the methods of two routers mounted on one path", () => {
|
|
137
|
+
expectTypeOf<keyof Schema["shared"]>().toEqualTypeOf<"$get" | "$post">();
|
|
138
|
+
expectTypeOf<ExtractResponseType<Schema["shared"]["$post"]>>().toEqualTypeOf<{ written: true }>();
|
|
139
|
+
expect(true).toBe(true);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
describe("HonoAppToHyperFetch [ Path shapes ]", () => {
|
|
144
|
+
it("should give a path registered without a leading slash the endpoint createSdk sends", () => {
|
|
145
|
+
expectTypeOf<ExtractEndpointType<Schema["plain"]["$get"]>>().toEqualTypeOf<"/plain">();
|
|
146
|
+
expect(true).toBe(true);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("should give a path registered with a trailing slash the endpoint createSdk sends", () => {
|
|
150
|
+
expectTypeOf<keyof Schema["slash"]>().toEqualTypeOf<"$get">();
|
|
151
|
+
expectTypeOf<ExtractEndpointType<Schema["slash"]["$get"]>>().toEqualTypeOf<"/slash">();
|
|
152
|
+
expect(true).toBe(true);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
it("should keep a wildcard segment as a literal * key", () => {
|
|
156
|
+
expectTypeOf<keyof Schema["assets"]>().toEqualTypeOf<"*">();
|
|
157
|
+
expectTypeOf<ExtractEndpointType<Schema["assets"]["*"]["$get"]>>().toEqualTypeOf<"/assets/*">();
|
|
158
|
+
expect(true).toBe(true);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it("should nest a route deeper than ten segments", () => {
|
|
162
|
+
type Leaf = Schema["l1"]["l2"]["l3"]["l4"]["l5"]["l6"]["l7"]["l8"]["l9"]["l10"]["l11"]["$leaf"]["$get"];
|
|
163
|
+
|
|
164
|
+
expectTypeOf<ExtractEndpointType<Leaf>>().toEqualTypeOf<"/l1/l2/l3/l4/l5/l6/l7/l8/l9/l10/l11/:leaf">();
|
|
165
|
+
expectTypeOf<ExtractResponseType<Leaf>>().toEqualTypeOf<{ leaf: string }>();
|
|
166
|
+
expect(true).toBe(true);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("should keep the default client below the ten levels createSdk injects its client into", () => {
|
|
170
|
+
const client = createClient({ url: "http://localhost" });
|
|
171
|
+
const sdk = createSdk<typeof client, Schema>(client);
|
|
172
|
+
const shallow = sdk.files.$get;
|
|
173
|
+
const deep = sdk.l1.l2.l3.l4.l5.l6.l7.l8.l9.l10.l11.$leaf.$get;
|
|
174
|
+
|
|
175
|
+
expectTypeOf<ExtractClientType<typeof shallow>>().toEqualTypeOf<typeof client>();
|
|
176
|
+
expectTypeOf<ExtractClientType<typeof deep>>().toEqualTypeOf<ClientInstance>();
|
|
177
|
+
deep.setParams({ leaf: "end" });
|
|
178
|
+
// @ts-expect-error - the param is named by the Hono path
|
|
179
|
+
deep.setParams({ id: "end" });
|
|
180
|
+
expect(true).toBe(true);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("should flatten routers mounted with an empty path", () => {
|
|
184
|
+
const app = new Hono().basePath("/api/v1").route(
|
|
185
|
+
"/me",
|
|
186
|
+
new Hono().route(
|
|
187
|
+
"",
|
|
188
|
+
new Hono().get("", (c) => c.json({ name: "hono" })),
|
|
189
|
+
),
|
|
190
|
+
);
|
|
191
|
+
type MeSchema = HonoAppToHyperFetch<typeof app>;
|
|
192
|
+
|
|
193
|
+
expectTypeOf<ExtractEndpointType<MeSchema["api"]["v1"]["me"]["$get"]>>().toEqualTypeOf<"/api/v1/me">();
|
|
194
|
+
expect(true).toBe(true);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("should prefix routes added after basePath()", () => {
|
|
198
|
+
const app = new Hono().basePath("/api").get("/search", (c) => c.json({ ok: true as const }));
|
|
199
|
+
type SearchSchema = HonoAppToHyperFetch<typeof app>;
|
|
200
|
+
|
|
201
|
+
expectTypeOf<ExtractEndpointType<SearchSchema["api"]["search"]["$get"]>>().toEqualTypeOf<"/api/search">();
|
|
202
|
+
expect(true).toBe(true);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("should prefix a router mounted after basePath()", () => {
|
|
206
|
+
const book = new Hono().get("/", (c) => c.json({ ok: true as const }));
|
|
207
|
+
const app = new Hono().basePath("/v1").route("/book", book);
|
|
208
|
+
type BookSchema = HonoAppToHyperFetch<typeof app>;
|
|
209
|
+
|
|
210
|
+
expectTypeOf<ExtractEndpointType<BookSchema["v1"]["book"]["$get"]>>().toEqualTypeOf<"/v1/book">();
|
|
211
|
+
expect(true).toBe(true);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("should accept an app with a typed environment", () => {
|
|
215
|
+
type Env = { Bindings: { TOKEN: string }; Variables: { userId: string } };
|
|
216
|
+
const api = new Hono<Env>().get("/me", (c) => c.json({ userId: c.get("userId") }));
|
|
217
|
+
const app = new Hono<Env>().route("/api", api);
|
|
218
|
+
type EnvSchema = HonoAppToHyperFetch<typeof app>;
|
|
219
|
+
|
|
220
|
+
expectTypeOf<ExtractResponseType<EnvSchema["api"]["me"]["$get"]>>().toEqualTypeOf<{ userId: string }>();
|
|
221
|
+
expect(true).toBe(true);
|
|
222
|
+
});
|
|
223
|
+
});
|
|
@@ -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
|
+
});
|